import { NextResponse } from "next/server";
import { resolveSamApiKey } from "@/lib/integrations/sam-gov";
import { fetchSamOpportunitiesForBusiness } from "@/lib/sam-gov/fetch-opportunities";
import type { OnboardingInput, Opportunity, SamGovIntegration } from "@/lib/types";

export async function POST(req: Request) {
  try {
    const body = (await req.json()) as {
      input: OnboardingInput;
      existingOpportunities?: Opportunity[];
      daysBack?: number;
      limit?: number;
      samGov?: SamGovIntegration;
      /** One-time key during connect flow before saved to business */
      apiKey?: string;
    };

    if (!body.input?.industry) {
      return NextResponse.json({ ok: false, error: "Business industry is required." }, { status: 400 });
    }

    const apiKey =
      body.apiKey?.trim() ||
      resolveSamApiKey(body.samGov) ||
      process.env.SAM_GOV_API_KEY?.trim();

    if (!apiKey) {
      return NextResponse.json(
        {
          ok: false,
          error:
            "No SAM.gov API key available. Connect SAM.gov in Settings or add SAM_GOV_API_KEY to the server.",
          needsConnection: true,
        },
        { status: 503 },
      );
    }

    const result = await fetchSamOpportunitiesForBusiness({
      apiKey,
      input: body.input,
      existingOpportunities: body.existingOpportunities,
      daysBack: body.daysBack ?? 90,
      limit: body.limit ?? 20,
    });

    return NextResponse.json({ ok: true, ...result });
  } catch (error) {
    return NextResponse.json(
      {
        ok: false,
        error: error instanceof Error ? error.message : "Failed to fetch SAM.gov opportunities",
      },
      { status: 500 },
    );
  }
}
