import { NextRequest, NextResponse } from 'next/server';
import { verifySession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { pgGetSettings, pgGetEmployees } from '@/lib/postgres/data-access';
import {
  pgGetAttendanceRecords,
  pgCreateAttendanceRecord,
  pgUpdateAttendanceRecord,
} from '@/lib/postgres/attendance';

export async function GET(request: NextRequest) {
  try {
    const session = await verifySession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const settings = await pgGetSettings();
    if (!hasEmployeePermission(session.user, settings, 'admin.hr-attendance')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const url = new URL(request.url);
    const page = Math.max(1, Number(url.searchParams.get('page') || 1));
    const pageSize = Math.max(10, Math.min(500, Number(url.searchParams.get('pageSize') || 50)));
    const employeeId = url.searchParams.get('employeeId') || undefined;
    const fromDate = url.searchParams.get('fromDate') || undefined;
    const toDate = url.searchParams.get('toDate') || undefined;
    const recordType = url.searchParams.get('recordType') || undefined;
    const status = url.searchParams.get('status') || undefined;

    const result = await pgGetAttendanceRecords({
      page,
      pageSize,
      employeeId: employeeId,
      fromDate,
      toDate,
      recordType,
      status,
    });

    return NextResponse.json(result);
  } catch (error) {
    console.error('Error fetching attendance records:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const session = await verifySession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const settings = await pgGetSettings();
    if (!hasEmployeePermission(session.user, settings, 'admin.hr-attendance')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await request.json();
    const {
      employeeId,
      date,
      recordType,
      checkInTime,
      checkOutTime,
      durationHours,
      lateMinutes,
      device,
      deviceId,
      notes,
      justification,
      justificationType,
      status,
    } = body;

    if (!employeeId || !date || !recordType || !device) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    const employees = await pgGetEmployees({ page: 1, pageSize: 10000 });
    const employee = employees.items?.find((e: any) => e.id === employeeId);
    if (!employee) {
      return NextResponse.json({ error: 'Employee not found' }, { status: 404 });
    }

    const record = await pgCreateAttendanceRecord({
      employeeId,
      date,
      recordType,
      checkInTime: checkInTime || undefined,
      checkOutTime: checkOutTime || undefined,
      durationHours: durationHours || undefined,
      lateMinutes: lateMinutes || 0,
      device,
      deviceId: deviceId || undefined,
      notes: notes || undefined,
      justification: justification || undefined,
      justificationType: justificationType || undefined,
      status: status || 'pending',
      createdBy: session.user.id,
    });

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