import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { withPermission, isErrorResponse } from '@/lib/auth/api-guard';

export const dynamic = 'force-dynamic';

// GET - Fetch HR data
export async function GET(request: NextRequest) {
  const auth = await withPermission(request, { resource: 'hr', action: 'read' });
  if (isErrorResponse(auth)) return auth;

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

    if (type === 'employees') {
      const employees = await prisma.employee.findMany({
        include: {
          department: { select: { name: true, code: true } },
          manager: { select: { firstName: true, lastName: true } },
        },
        orderBy: { lastName: 'asc' },
      });
      return NextResponse.json({ success: true, employees });
    }

    if (type === 'departments') {
      const departments = await prisma.department.findMany({
        include: { _count: { select: { employees: true } } },
        orderBy: { name: 'asc' },
      });
      return NextResponse.json({ success: true, departments });
    }

    if (type === 'payroll') {
      const period = searchParams.get('period');
      const payroll = await prisma.payrollRecord.findMany({
        where: period ? { period } : {},
        include: { employee: { select: { firstName: true, lastName: true, employeeId: true } } },
        orderBy: { createdAt: 'desc' },
        take: 100,
      });
      return NextResponse.json({ success: true, payroll });
    }

    if (type === 'time-entries') {
      const timeEntries = await prisma.timeEntry.findMany({
        include: { employee: { select: { firstName: true, lastName: true } } },
        orderBy: { date: 'desc' },
        take: 100,
      });
      return NextResponse.json({ success: true, timeEntries });
    }

    if (type === 'leave-requests') {
      const leaveRequests = await prisma.leaveRequest.findMany({
        include: { employee: { select: { firstName: true, lastName: true } } },
        orderBy: { createdAt: 'desc' },
        take: 50,
      });
      return NextResponse.json({ success: true, leaveRequests });
    }

    // Summary
    const [employees, departments, pendingLeave, recentPayroll] = await Promise.all([
      prisma.employee.findMany({ where: { status: 'active' } }),
      prisma.department.findMany({ where: { isActive: true } }),
      prisma.leaveRequest.findMany({ 
        where: { status: 'pending' },
        include: { employee: { select: { firstName: true, lastName: true } } }
      }),
      prisma.payrollRecord.findMany({ take: 5, orderBy: { createdAt: 'desc' } }),
    ]);

    const totalEmployees = employees.length;
    const fullTime = employees.filter((e: any) => e.employmentType === 'full-time').length;
    const partTime = employees.filter((e: any) => e.employmentType === 'part-time').length;
    const contractors = employees.filter((e: any) => e.employmentType === 'contractor').length;
    const totalSalary = employees.reduce((sum: number, e: any) => sum + (e.salary || 0), 0);

    // Filter out any records with missing employee relations
    const validPendingLeave = pendingLeave.filter((leave: any) => leave.employee && leave.employee.firstName);

    return NextResponse.json({
      success: true,
      summary: {
        totalEmployees,
        fullTime,
        partTime,
        contractors,
        departmentCount: departments.length,
        pendingLeaveRequests: validPendingLeave.length,
        monthlyPayroll: totalSalary,
        avgSalary: totalEmployees > 0 ? totalSalary / totalEmployees : 0,
      },
      departments: departments.slice(0, 5),
      pendingLeave: validPendingLeave.slice(0, 5),
      recentPayroll,
    });
  } catch (error) {
    console.error('HR API error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch HR data' }, { status: 500 });
  }
}

// POST - Create new employee/department/etc
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { entity, data } = body;

    if (entity === 'employee') {
      const employee = await prisma.employee.create({
        data,
        include: { department: true },
      });
      // Update department headcount
      if (data.departmentId) {
        await prisma.department.update({
          where: { id: data.departmentId },
          data: { headCount: { increment: 1 } },
        });
      }
      return NextResponse.json({ success: true, employee });
    }

    if (entity === 'department') {
      const department = await prisma.department.create({ data });
      return NextResponse.json({ success: true, department });
    }

    if (entity === 'time-entry') {
      const totalHours = data.clockOut && data.clockIn
        ? (new Date(data.clockOut).getTime() - new Date(data.clockIn).getTime()) / (1000 * 60 * 60) - (data.breakMinutes || 0) / 60
        : null;
      const timeEntry = await prisma.timeEntry.create({
        data: { ...data, totalHours },
      });
      return NextResponse.json({ success: true, timeEntry });
    }

    if (entity === 'leave-request') {
      const leaveRequest = await prisma.leaveRequest.create({ data });
      return NextResponse.json({ success: true, leaveRequest });
    }

    if (entity === 'payroll') {
      const payroll = await prisma.payrollRecord.create({ data });
      return NextResponse.json({ success: true, payroll });
    }

    return NextResponse.json({ success: false, error: 'Invalid entity type' }, { status: 400 });
  } catch (error) {
    console.error('HR POST error:', error);
    return NextResponse.json({ success: false, error: 'Failed to create record' }, { status: 500 });
  }
}

// PATCH - Update leave request status, etc
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { entity, id, data } = body;

    if (entity === 'leave-request') {
      const leaveRequest = await prisma.leaveRequest.update({
        where: { id },
        data: {
          ...data,
          approvedAt: data.status === 'approved' ? new Date() : undefined,
        },
      });
      return NextResponse.json({ success: true, leaveRequest });
    }

    if (entity === 'employee') {
      const employee = await prisma.employee.update({
        where: { id },
        data,
      });
      return NextResponse.json({ success: true, employee });
    }

    return NextResponse.json({ success: false, error: 'Invalid entity type' }, { status: 400 });
  } catch (error) {
    console.error('HR PATCH error:', error);
    return NextResponse.json({ success: false, error: 'Failed to update record' }, { status: 500 });
  }
}
