import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import prisma from '@/lib/prisma';

// GET - Fetch payroll records
export async function GET(request: Request) {
  try {
    const session = await getServerSession();
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const month = searchParams.get('month');
    const year = searchParams.get('year');

    const where: any = {};
    if (month) where.month = month;
    if (year) where.year = parseInt(year);

    const payrollRecords = await prisma.payrollRecord.findMany({
      where,
      orderBy: { createdAt: 'desc' }
    });

    return NextResponse.json(payrollRecords);
  } catch (error) {
    console.error('Error fetching payroll records:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

// POST - Create payroll record
export async function POST(request: Request) {
  try {
    const session = await getServerSession();
    if (!session || (((session.user as any)?.role !== 'admin' && (session.user as any)?.role !== 'hr' && (session.user as any)?.role !== 'finance'))) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { employeeId, month, year, grossSalary, deductions, netSalary } = body;

    const payrollRecord = await prisma.payrollRecord.create({
      data: {
        employeeId,
        month,
        year,
        basicSalary: grossSalary || 0,
        houseAllowance: 0,
        transportAllowance: 0,
        otherAllowances: 0,
        grossPay: grossSalary || 0,
        paye: 0,
        nhif: 0,
        nssf: 0,
        otherDeductions: deductions || 0,
        netPay: netSalary || 0,
        status: 'Pending'
      }
    });

    return NextResponse.json(payrollRecord, { status: 201 });
  } catch (error) {
    console.error('Error creating payroll record:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}