import { NextResponse } from "next/server";
import { assertAccountOwnedByUser } from "@/lib/auth/accounts";
import { authErrorResponse } from "@/lib/auth/api";
import { requireSessionUser } from "@/lib/auth/session";
import { enqueueJob, findActiveAccountJob } from "@/lib/jobs/runner";
import { scheduleBackgroundJob } from "@/lib/jobs/schedule";

export const maxDuration = 180;

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const user = await requireSessionUser();
    const { id } = await params;
    await assertAccountOwnedByUser(user.id, id);
    const body = (await request.json()) as { benchmarkUsername?: string };
    const username = body.benchmarkUsername?.replace(/^@/, "").trim();
    if (!username) return NextResponse.json({ error: "請輸入對標帳號" }, { status: 400 });

    const existing = await findActiveAccountJob(id, "style-8d");
    if (existing) {
      return NextResponse.json({
        jobId: existing.id,
        status: existing.status,
        message: "這個帳號已有 8D 分析任務進行中",
      });
    }

    const job = await enqueueJob({
      type: "style-8d",
      accountId: id,
      label: `@${username} · 8D 帳號風格`,
      payload: { accountId: id, benchmarkUsername: username },
    });
    scheduleBackgroundJob(job.id);
    return NextResponse.json({ jobId: job.id, status: "pending", message: "8D 分析已在背景執行" });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    return NextResponse.json({ error: error instanceof Error ? error.message : "8D 分析失敗" }, { status: 500 });
  }
}
