import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const CategorisationBodySchema = z.object({
  portfolio_id: z.number(),
  scenarios_to_consider: z.array(z.number()).optional(),
  scenario_priority_order: z.array(z.number()).optional(),
})

export async function POST(request: NextRequest) {
  console.log("API hit");
  const body = await request.json();
  let validatedBody;

  try {
    validatedBody = CategorisationBodySchema.parse(body);
  } catch (error) {
    console.error("Invalid input: ", error);
    return new NextResponse(JSON.stringify({ msg: "Invalid input" }), {
      status: 400,
    });
  }

  try {
    // This triggers the work distribution, but doesn't wait for the lambdas to complete categorisation
    // Instead we'll check the task ID before allowing user to select the new recommendations
    const headers = {
      "x-api-key": process.env.FASTAPI_API_KEY || "",
      Authorization: `Bearer ${
        request.cookies.get("__Secure-next-auth.session-token")?.value ||
        request.cookies.get("next-auth.session-token")?.value
      }`,
      "Content-Type": "application/json",
    };

    const url = `${process.env.FASTAPI_API_URL}/v1/plan/categorisation`;

    console.log("Request:", url, validatedBody);

    const response = await fetch(url, {
      method: "POST",
      headers: headers,
      body: JSON.stringify(validatedBody),
    });

    if (!response.ok) {
      console.error("Error triggering plan:", response.statusText);
      return new NextResponse(
        JSON.stringify({ msg: "Error triggering plan" }),
        {
          status: 500,
        },
      );
    }

    return new NextResponse(JSON.stringify({ msg: "Categorisation job started" }), {
      status: 200,
    });

  } catch (error) {
    console.error(error);
    return new NextResponse(JSON.stringify({ msg: "Internal server error" }), {
      status: 500,
    });
  }

}