import { NextResponse } from "next/server";
import { regenerateSearchTags } from "@/lib/ai/analyze-topic";
import { parseProviderApiKeys } from "@/lib/ai/keys";
import { getActiveAccountId } from "@/lib/account-context";
import { authErrorResponse } from "@/lib/auth/api";
import { isAccountInUserScope, requireUserAccountScope } from "@/lib/auth/user-scope";
import { prisma } from "@/lib/db";
import { pickDefaultSelectedTags } from "@/lib/services/scan-tasks";
import { getOrCreateSettings } from "@/lib/user-settings";
import { parseResearchMap } from "@/lib/types/research";

export const maxDuration = 120;

export async function POST(request: Request) {
  try {
    const { topicId } = (await request.json()) as { topicId?: string };
    if (!topicId) {
      return NextResponse.json({ error: "缺少 topicId" }, { status: 400 });
    }

    const { accountIds } = await requireUserAccountScope(await getActiveAccountId());
    const topic = await prisma.topic.findUnique({ where: { id: topicId } });
    if (!topic || !isAccountInUserScope(accountIds, topic.accountId)) {
      return NextResponse.json({ error: "找不到主題" }, { status: 404 });
    }
    const currentMap = parseResearchMap(topic.researchMap);
    if (!currentMap) {
      return NextResponse.json({ error: "請先完成一次主題分析，建立研究地圖" }, { status: 400 });
    }

    const settings = await getOrCreateSettings();
    const tags = await regenerateSearchTags({
      label: topic.label,
      query: topic.query,
      brief: topic.brief,
      topicGoal: topic.topicGoal,
      aiProvider: settings.researchAiProvider ?? settings.aiProvider,
      aiModel: settings.researchAiModel ?? settings.aiModel,
      apiKeys: parseProviderApiKeys(settings.providerApiKeys),
    }, currentMap);

    const accountTags = currentMap.suggestedTags.filter(
      (tag) => tag.searchType === "帳號" || tag.tag.startsWith("@")
    );
    const researchMap = {
      ...currentMap,
      suggestedTags: [...tags, ...accountTags].slice(0, 14),
    };
    const selectedTags = pickDefaultSelectedTags(researchMap, topic.topicGoal);

    await prisma.topic.update({
      where: { id: topic.id },
      data: {
        researchMap: JSON.stringify(researchMap),
        selectedTags: JSON.stringify(selectedTags),
      },
    });

    return NextResponse.json({ researchMap, selectedTags, count: tags.length });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    const message = error instanceof Error ? error.message : "搜尋標籤分析失敗";
    console.error("[analyze-tags] failed:", error);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
