import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getOrCreateSettings } from "@/lib/user-settings";
import { factCheckDraft } from "@/lib/ai/fact-check";
import { parseProviderApiKeys } from "@/lib/ai/keys";
import { trackAiTask } from "@/lib/jobs/track";

export const maxDuration = 120;

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as { draftId?: string; text?: string };
    const settings = await getOrCreateSettings();
    const apiKeys = parseProviderApiKeys(settings.providerApiKeys);

    let text = body.text;
    let angle: string | null | undefined;
    let searchTag: string | null | undefined;
    let topicLabel: string | null | undefined;

    if (body.draftId) {
      const draft = await prisma.draft.findUnique({ where: { id: body.draftId } });
      if (!draft) {
        return NextResponse.json({ error: "找不到草稿" }, { status: 404 });
      }
      text = draft.text;
      angle = draft.angle;
      searchTag = draft.searchTag;
      if (draft.topicId) {
        const topic = await prisma.topic.findUnique({ where: { id: draft.topicId } });
        topicLabel = topic?.label;
      }
    }

    if (!text?.trim()) {
      return NextResponse.json({ error: "缺少貼文內容" }, { status: 400 });
    }

    const result = await trackAiTask("貼文事實查核", () => factCheckDraft({
      text: text.trim(),
      angle,
      searchTag,
      topicLabel,
      aiProvider: settings.aiProvider,
      aiModel: settings.aiModel,
      apiKeys,
    }));

    if (body.draftId) {
      await prisma.draft.update({
        where: { id: body.draftId },
        data: { factCheckResult: JSON.stringify(result) },
      });
    }

    return NextResponse.json({ factCheck: result });
  } catch (error) {
    const message = error instanceof Error ? error.message : "查證失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
