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

export const loader = async ({ request }: LoaderFunctionArgs) => {
  await requireAuthLevel(request, 2); // Only supervisors and admins

  const url = new URL(request.url);
  const category = url.searchParams.get('category');
  const model = url.searchParams.get('model');
  const number = url.searchParams.get('number');
  const dateFrom = url.searchParams.get('dateFrom');
  const dateTo = url.searchParams.get('dateTo');

  if (!category || !model || !number) {
    return json({ error: "Equipment details are required" }, { status: 400 });
  }

  // Build where clause for reports
  const whereClause: any = {};

  // Add date filters if provided
  if (dateFrom || dateTo) {
    whereClause.createdDate = {};
    if (dateFrom) {
      whereClause.createdDate.gte = new Date(dateFrom + 'T00:00:00.000Z');
    }
    if (dateTo) {
      whereClause.createdDate.lte = new Date(dateTo + 'T23:59:59.999Z');
    }
  }

  // Fetch all reports that match the date filter
  const reports = await prisma.report.findMany({
    where: whereClause,
    orderBy: { createdDate: 'desc' },
    include: {
      employee: { select: { name: true } },
      area: { select: { name: true } }
    }
  });

  // Filter reports that have this equipment in their timeSheet
  // Equipment machine format in timeSheet: "Model (Number)"
  const equipmentMachine = `${model} (${number})`;
  const usage: any[] = [];

  reports.forEach((report) => {
    const timeSheet = report.timeSheet as any[];
    if (Array.isArray(timeSheet) && timeSheet.length > 0) {
      timeSheet.forEach((entry: any) => {
        // Check if the machine matches (trim whitespace)
        const entryMachine = (entry.machine || '').trim();
        const searchMachine = equipmentMachine.trim();
        
        if (entryMachine === searchMachine) {
          usage.push({
            createdDate: report.createdDate,
            shift: report.shift,
            area: report.area,
            employee: report.employee,
            totalHours: entry.total || '00:00',
            reason: entry.reason || ''
          });
        }
      });
    }
  });

  return json({ usage });
};
