import { NextRequest, NextResponse } from "next/server";
import { db } from "@/app/db/db";
import { z } from "zod";
import { formatNumber } from "@/app/utils";
import { DataItem, ChartData } from "@/app/portfolio/[slug]/utils";
import { eq } from "drizzle-orm";
import { scenario } from "@/app/db/schema/recommendations";

export async function GET(
  request: NextRequest,
  props: { params: Promise<{ scenarioId: string }> },
) {
  const params = await props.params;
  const scenarioId = params.scenarioId;

  const data = await db
    .select({
      name: scenario.name,
      cost: scenario.cost,
      funding: scenario.funding,
      contingency: scenario.contingency,
      epcBreakdownPostRetrofit: scenario.epcBreakdownPostRetrofit,
      numberOfProperties: scenario.numberOfProperties,
      nUnitsToRetrofit: scenario.nUnitsToRetrofit,
      co2PerUnitPostRetrofit: scenario.co2PerUnitPostRetrofit,
      energyBillPerUnitPostRetrofit: scenario.energyBillPerUnitPostRetrofit,
      energyConsumptionPerUnitPostRetrofit:
        scenario.energyConsumptionPerUnitPostRetrofit,
      valuationImprovementPerUnit: scenario.valuationImprovementPerUnit,
      costPerUnit: scenario.costPerUnit,
      costPerCo2Saved: scenario.costPerCo2Saved,
      costPerSapPoint: scenario.costPerSapPoint,
      valuationReturnOnInvestment: scenario.valuationReturnOnInvestment,
    })
    .from(scenario)
    .where(eq(scenario.id, BigInt(scenarioId)));

  if (data.length === 0) {
    throw new Error("Scenario not found");
  }

  if (data.length > 1) {
    throw new Error("More than one scenario found");
  }

  const scenarioName = data[0].name || "Default";

  // Format the data we need for the overview
  const output: DataItem[] = [
    {
      title: "EPCs",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: JSON.parse(
            data[0].epcBreakdownPostRetrofit || "[]",
          ) as ChartData[],
        },
      ],
    },
    {
      title: "# Units",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: String(data[0].numberOfProperties) || "",
        },
      ],
    },
    {
      title: "# Units to retrofit",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: String(data[0].nUnitsToRetrofit) || "",
        },
      ],
    },
    {
      title: "CO2/unit",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: data[0].co2PerUnitPostRetrofit || "",
        },
      ],
    },
    {
      title: "Annual energy bill/unit",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: data[0].energyBillPerUnitPostRetrofit || "",
        },
      ],
    },
    {
      title: "Annual energy demand (kWh)/unit",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: data[0].energyConsumptionPerUnitPostRetrofit || "",
        },
      ],
    },
    {
      title: "Cost of works (£)",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: "£" + formatNumber(data[0].cost || 0),
        },
      ],
    },
    {
      title: "Cost of works (£)/unit",
      scenarios: [
        { scenarioName: scenarioName, data: data[0].costPerUnit || "" },
      ],
    },
    {
      title: "Funding (£)",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: "£" + formatNumber(data[0].funding || 0),
        },
      ],
    },
    {
      title: "Funding (£)/unit",
      scenarios: [
        {
          scenarioName: scenarioName,
          data:
            "£" +
            formatNumber(
              (data[0].funding || 0) / (data[0].nUnitsToRetrofit || 1),
            ),
        },
      ],
    },
    {
      title: "Contingency (£)",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: "£" + formatNumber(data[0].contingency || 0),
        },
      ],
    },
    {
      title: "Contingency (£)/unit",
      scenarios: [
        {
          scenarioName: scenarioName,
          data:
            "£" +
            formatNumber(
              (data[0].contingency || 0) / (data[0].nUnitsToRetrofit || 1),
            ),
        },
      ],
    },
    {
      title: "£ per CO2 reduction",
      scenarios: [
        { scenarioName: scenarioName, data: data[0].costPerCo2Saved || "" },
      ],
    },
    {
      title: "£ per SAP point",
      scenarios: [
        { scenarioName: scenarioName, data: data[0].costPerSapPoint || "" },
      ],
    },
    {
      title:
        "Potential valuation improvement/unit - highly indicative EPC effect*",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: data[0].valuationImprovementPerUnit || "",
        },
      ],
    },
    {
      title:
        "Potential valuation return on investment - highly indicative EPC effect*",
      scenarios: [
        {
          scenarioName: scenarioName,
          data: data[0].valuationReturnOnInvestment || "",
        },
      ],
    },
  ];

  return new NextResponse(JSON.stringify(output), {
    status: 200,
  });
}
