import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { prisma } from "~/utils/db.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const areaId = url.searchParams.get("areaId");
  const dredgerLocationId = url.searchParams.get("dredgerLocationId");
  const reclamationLocationId = url.searchParams.get("reclamationLocationId");

  if (!areaId || !dredgerLocationId || !reclamationLocationId) {
    return json({ data: null });
  }

  try {
    // Find the most recent report for this location combination
    const lastReport = await prisma.report.findFirst({
      where: {
        areaId: parseInt(areaId),
        dredgerLocationId: parseInt(dredgerLocationId),
        reclamationLocationId: parseInt(reclamationLocationId),
      },
      orderBy: {
        createdDate: 'desc',
      },
      select: {
        dredgerLineLength: true,
        shoreConnection: true,
        reclamationHeight: true,
        pipelineLength: true,
      },
    });

    if (!lastReport) {
      return json({ data: null });
    }

    const reclamationHeight = lastReport.reclamationHeight as any;
    const pipelineLength = lastReport.pipelineLength as any;

    // Calculate carry-forward values
    const carryForwardData = {
      dredgerLineLength: lastReport.dredgerLineLength,
      shoreConnection: lastReport.shoreConnection,
      reclamationHeightBase: (reclamationHeight.base || 0) + (reclamationHeight.extra || 0),
      pipelineMain: (pipelineLength.main || 0) + (pipelineLength.ext1 || 0),
      pipelineReserve: (pipelineLength.reserve || 0) + (pipelineLength.ext2 || 0),
    };

    return json({ data: carryForwardData });
  } catch (error) {
    console.error("Error fetching last report data:", error);
    return json({ data: null });
  }
};
