import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getActiveAccountId } from "@/lib/account-context";
import { generateDraftsForScan } from "@/lib/services/generate";
import { trackAiTask } from "@/lib/jobs/track";

export const maxDuration = 120;

export async function POST(request: Request) {
  try {
    const { scanId } = (await request.json()) as { scanId?: string };
    if (!scanId) {
      return NextResponse.json({ error: "缺少 scanId" }, { status: 400 });
    }
    const accountId = await getActiveAccountId();
    const scan = await prisma.scan.findUnique({ where: { id: scanId } });
    if (!scan || (accountId && scan.accountId !== accountId)) {
      return NextResponse.json({ error: "找不到海巡紀錄" }, { status: 404 });
    }

    const drafts = await trackAiTask("生成貼文草稿", () => generateDraftsForScan(scanId));
    return NextResponse.json({ drafts });
  } catch (error) {
    const message = error instanceof Error ? error.message : "生成草稿失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
