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

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

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

  const db = await readDb();
  if (!db.boards.some((board) => board.id === boardId)) {
    return NextResponse.json({ error: "board not found" }, { status: 404 });
  }
  const now = new Date().toISOString();
  const pinDraft: PinterestPinDraft = {
    id: createId("pin"),
    boardId,
    title,
    description: String(body.description || ""),
    link: body.link ? String(body.link) : undefined,
    mediaUrl: body.mediaUrl ? String(body.mediaUrl) : undefined,
    mediaType: body.mediaType === "video" ? "video" : "image",
    keywords: Array.isArray(body.keywords) ? body.keywords.map(String) : [],
    status: "pending_review",
    scheduledAt: body.scheduledAt ? String(body.scheduledAt) : undefined,
    createdAt: now,
    updatedAt: now,
  };
  db.pinDrafts.unshift(pinDraft);
  addAudit(db, {
    type: "content",
    actor: "user",
    title: "创建 Pin 草稿",
    detail: pinDraft.title,
    status: "review",
  });
  await writeDb(db);
  return NextResponse.json({ pinDraft });
}
