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

const BodySchema = z.object({
  folderKey: z.string(),
  userId: z.string(),
  scheme: z.string(),
});

export async function POST(request: NextRequest) {
  const body = await request.json();
  let validatedBody;

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

  try {
    // We'll trigger the plan build in our fastapi backend and then the user will just have to
    // wait for the plan to be ready

    const headers = {
      "Content-Type": "application/json",
    };

    console.log("validatedBody", validatedBody);

    const response = await fetch(
      `${process.env.DUE_CONSIDERATIONS_API_URL}/due-considerations`,
      {
        method: "POST",
        headers: headers,
        body: JSON.stringify(validatedBody),
      }
    );

    if (!response.ok) {
      throw new Error("API request failed");
    }

    const responseData = await response.json();

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