import { NextResponse } from "next/server";
import { getOrCreateSettings } from "@/lib/user-settings";
import { generateAccountStrategy, type AccountStrategyFields } from "@/lib/ai/generate-account-strategy";
import { parseProviderApiKeys } from "@/lib/ai/keys";
import { trackAiTask } from "@/lib/jobs/track";

export const maxDuration = 60;

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as {
      instruction?: string;
      current?: Partial<AccountStrategyFields>;
    };

    const instruction = body.instruction?.trim();
    if (!instruction) {
      return NextResponse.json({ error: "請先跟小幫手說你想經營什麼方向" }, { status: 400 });
    }

    const settings = await getOrCreateSettings();
    const apiKeys = parseProviderApiKeys(settings.providerApiKeys);
    const result = await trackAiTask("帳號策略助手", () => generateAccountStrategy({
      instruction,
      current: body.current ?? {},
      aiProvider: settings.aiProvider,
      aiModel: settings.aiModel,
      apiKeys,
    }));

    return NextResponse.json(result);
  } catch (error) {
    const message = error instanceof Error ? error.message : "策略小幫手暫時無法產生內容";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
