﻿import { NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-helper';
import prisma from '@/lib/prisma';

// GET - Fetch leave requests
export async function GET(request: Request) {
  const auth = await requireAuth(['admin', 'hr']);
  if (auth.error) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');

    const where: any = {};
    if (status && status !== 'All') where.status = status;

    const leaveRequests = await prisma.leaveRequest.findMany({
      where,
      orderBy: { submittedOn: 'desc' }
    });

    return NextResponse.json(leaveRequests);
  } catch (error) {
    console.error('Error fetching leave requests:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

// POST - Create leave request
export async function POST(request: Request) {
  const auth = await requireAuth();
  if (auth.error) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  try {
    const body = await request.json();
    const { employeeId, leaveType, startDate, endDate, reason } = body;

    const employee = await prisma.employee.findFirst({ where: { employeeNumber: employeeId } });
    const empName = employee?.fullName || '';
    const dept = employee?.dept || '';
    const position = employee?.position || '';
    const employeeType = employee?.employmentType || 'Permanent';
    const gender = employee?.gender || 'Unknown';

    const s = new Date(startDate);
    const e = new Date(endDate);
    const msPerDay = 1000 * 60 * 60 * 24;
    const days = Math.max(1, Math.round((e.getTime() - s.getTime()) / msPerDay) + 1);

    const leaveRequest = await prisma.leaveRequest.create({
      data: {
        employeeId,
        employeeName: empName,
        dept,
        position,
        employeeType,
        gender,
        type: leaveType,
        startDate: new Date(startDate),
        endDate: new Date(endDate),
        days,
        reason,
        status: 'Pending',
        submittedOn: new Date()
      }
    });

    return NextResponse.json(leaveRequest, { status: 201 });
  } catch (error) {
    console.error('Error creating leave request:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
