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

export const action = async ({ request }: ActionFunctionArgs) => {
  await requireAuthLevel(request, 1);

  if (request.method !== "POST") {
    return json({ error: "Method not allowed" }, { status: 405 });
  }

  try {
    const { createdDate, shift, areaId, dredgerLocationId, reclamationLocationId } = await request.json();

    // Parse the date and set to start of day
    const date = new Date(createdDate);
    date.setHours(0, 0, 0, 0);

    const nextDay = new Date(date);
    nextDay.setDate(nextDay.getDate() + 1);

    // Check if a report already exists with same date, shift, area, dredger location, and reclamation location
    const existingReport = await prisma.report.findFirst({
      where: {
        createdDate: {
          gte: date,
          lt: nextDay
        },
        shift,
        areaId: parseInt(areaId),
        dredgerLocationId: parseInt(dredgerLocationId),
        reclamationLocationId: parseInt(reclamationLocationId)
      }
    });

    return json({ exists: !!existingReport });
  } catch (error) {
    console.error("Error checking for duplicate report:", error);
    return json({ error: "Failed to check for duplicate" }, { status: 500 });
  }
};
