import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { MeasureKeyEnum } from "@/app/db/schema/recommendations";
import { PortfolioGoal } from "@/app/db/schema/portfolio";

const PresignedUrlBodySchema = z
  .object({
    portfolio_id: z.string(),
    housing_type: z.enum(["Social", "Private"]),
    goal: z.enum(PortfolioGoal),
    goal_value: z.string().nullable(), // Nullable to handle cases where goal_value is not applicable
    trigger_file_path: z.string(),
    valuation_file_path: z.string(),
    multi_plan: z.boolean().optional(),
    budget: z.number().optional().nullable(),
    scenario_name: z.string().optional(),
    sheet_count: z.number().optional(), // Number of rows in the selected sheet
    event_type: z.enum(["remote_assessment"]).optional(),
    ashp_cop: z.number().optional(),
    // inclusions is a list of measures, where the values are in measuresList
    inclusions: z.array(MeasureKeyEnum).optional(),
    exclusions: z.array(MeasureKeyEnum).optional(),
    already_installed_file_path: z.string().optional(),
    // optional scenario_id to link the plan to an existing scenario
    scenario_id: z.string().optional().nullable(),
    file_type: z.enum(["csv", "xlsx"]).optional(), // Specify the file type
    file_format: z.enum(["domna_asset_list"]).optional().nullable(), // Specify the file format
    sheet_name: z.string().optional().nullable(), // Specify the sheet name if applicable
    enforce_fabric_first: z.boolean().optional().default(false),
  })
  .refine((data) => data.goal !== "Increasing EPC" || !!data.goal_value, {
    path: ["goal_value"],
    message: "Target EPC Rating is required when goal is Increasing EPC",
  });

export async function POST(request: NextRequest) {
  // For the moment, this api specifically handles uploads of csvs

  const body = await request.json();
  let validatedBody;

  try {
    validatedBody = PresignedUrlBodySchema.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 = {
      "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",
    };

    console.log("Triggering plan with body: ", validatedBody);

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

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

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

    const data = await response.json();

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