import { NextRequest, NextResponse } from "next/server";
import { addAudit, readDb, writeDb } from "@/lib/store";
import { createOperatorPlan } from "@/lib/operator-plan";

export async function GET() {
  const db = await readDb();
  return NextResponse.json({ plans: db.operatorPlans });
}

export async function POST(req: NextRequest) {
  const body = await req.json().catch(() => ({}));
  const command = String(body.command || body.goal || "").trim();
  if (!command) return NextResponse.json({ error: "command required" }, { status: 400 });

  const db = await readDb();
  const plan = createOperatorPlan({
    command,
    goal: body.goal,
    date: body.date,
    keyword: body.keyword,
    productUrl: body.productUrl,
    contentBrief: body.contentBrief,
  });
  db.operatorPlans.unshift(plan);
  addAudit(db, {
    type: "task",
    actor: "openclaw",
    title: "创建 Pinterest 运营计划",
    detail: plan.goal,
    status: "completed",
  });
  await writeDb(db);
  return NextResponse.json({ plan });
}
