import { prisma } from "~/utils/db.server";

export async function manageSheet(reportId: number, shift: string, areaId: number, dredgerLocationId: number, reclamationLocationId: number, createdDate: Date) {
  // Format date as YYYY-MM-DD
  const dateString = createdDate.toISOString().split('T')[0];
  
  try {
    // Check if a sheet already exists for this combination
    const existingSheet = await prisma.sheet.findUnique({
      where: {
        areaId_dredgerLocationId_reclamationLocationId_date: {
          areaId,
          dredgerLocationId,
          reclamationLocationId,
          date: dateString
        }
      }
    });

    if (existingSheet) {
      // Sheet exists, update it with the new shift
      if (shift === 'day' && !existingSheet.dayShiftId) {
        await prisma.sheet.update({
          where: { id: existingSheet.id },
          data: {
            dayShiftId: reportId,
            status: existingSheet.nightShiftId ? 'completed' : 'pending'
          }
        });
      } else if (shift === 'night' && !existingSheet.nightShiftId) {
        await prisma.sheet.update({
          where: { id: existingSheet.id },
          data: {
            nightShiftId: reportId,
            status: existingSheet.dayShiftId ? 'completed' : 'pending'
          }
        });
      }
    } else {
      // No sheet exists, create a new one
      const sheetData: any = {
        areaId,
        dredgerLocationId,
        reclamationLocationId,
        date: dateString,
        status: 'pending'
      };

      if (shift === 'day') {
        sheetData.dayShiftId = reportId;
      } else if (shift === 'night') {
        sheetData.nightShiftId = reportId;
      }

      await prisma.sheet.create({
        data: sheetData
      });
    }
  } catch (error) {
    console.error('Error managing sheet:', error);
    throw error;
  }
}

export async function removeFromSheet(reportId: number, shift: string, areaId: number, dredgerLocationId: number, reclamationLocationId: number, createdDate: Date) {
  // Format date as YYYY-MM-DD
  const dateString = createdDate.toISOString().split('T')[0];
  
  try {
    // Find the sheet for this combination
    const existingSheet = await prisma.sheet.findUnique({
      where: {
        areaId_dredgerLocationId_reclamationLocationId_date: {
          areaId,
          dredgerLocationId,
          reclamationLocationId,
          date: dateString
        }
      }
    });

    if (existingSheet) {
      if (shift === 'day' && existingSheet.dayShiftId === reportId) {
        if (existingSheet.nightShiftId) {
          // Keep sheet but remove day shift
          await prisma.sheet.update({
            where: { id: existingSheet.id },
            data: {
              dayShiftId: null,
              status: 'pending'
            }
          });
        } else {
          // Delete sheet if no other shift
          await prisma.sheet.delete({
            where: { id: existingSheet.id }
          });
        }
      } else if (shift === 'night' && existingSheet.nightShiftId === reportId) {
        if (existingSheet.dayShiftId) {
          // Keep sheet but remove night shift
          await prisma.sheet.update({
            where: { id: existingSheet.id },
            data: {
              nightShiftId: null,
              status: 'pending'
            }
          });
        } else {
          // Delete sheet if no other shift
          await prisma.sheet.delete({
            where: { id: existingSheet.id }
          });
        }
      }
    }
  } catch (error) {
    console.error('Error removing from sheet:', error);
    throw error;
  }
}