import { NextResponse } from "next/server";
import { analyzeScanItemViral, analyzeScanTopViral } from "@/lib/services/viral";
import { trackAiTask } from "@/lib/jobs/track";

export const maxDuration = 300;

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as { scanItemId?: string; scanId?: string; limit?: number };

    if (body.scanItemId) {
      const result = await trackAiTask("分析爆文結構", () => analyzeScanItemViral(body.scanItemId!));
      return NextResponse.json(result);
    }

    if (body.scanId) {
      const results = await trackAiTask("批次分析爆文結構", () => analyzeScanTopViral(body.scanId!, body.limit ?? 5));
      return NextResponse.json({ results });
    }

    return NextResponse.json({ error: "請提供 scanItemId 或 scanId" }, { status: 400 });
  } catch (error) {
    const message = error instanceof Error ? error.message : "爆款分析失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
