import { NextRequest, NextResponse } from "next/server";
import { checkCommercialGateWithHeartbeat } from "@/lib/commercial";
import { addAudit, createId, readDb, writeDb } from "@/lib/store";
import { PinterestAutomationTask } from "@/lib/types";

export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  const body = await req.json().catch(() => ({}));
  const db = await readDb();
  const pin = db.pinDrafts.find((item) => item.id === params.id);
  if (!pin) return NextResponse.json({ error: "pin draft not found" }, { status: 404 });
  const gate = await checkCommercialGateWithHeartbeat(db, "pin_publish");
  if (!gate.ok) {
    await writeDb(db);
    return NextResponse.json({ ok: false, error: gate.error, snapshot: gate.snapshot }, { status: gate.status });
  }

  const now = new Date().toISOString();
  pin.status = body.scheduleOnly === true ? "scheduled" : "scheduled";
  pin.scheduledAt = body.scheduledAt ? String(body.scheduledAt) : pin.scheduledAt || now;
  pin.updatedAt = now;

  const task: PinterestAutomationTask = {
    id: createId("task"),
    type: "publish_pin",
    executorMode: "api",
    status: "pending",
    payload: { pinDraftId: pin.id },
    createdAt: now,
    updatedAt: now,
  };
  db.tasks.unshift(task);
  addAudit(db, {
    type: "content",
    actor: "user",
    title: "批准 Pin 发布",
    detail: `${pin.title} -> task ${task.id}`,
    status: "review",
  });
  await writeDb(db);
  return NextResponse.json({ pinDraft: pin, task });
}
