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

function canAccess(user: any, settings: Record<string, unknown>) {
  return (
    hasEmployeePermission(user, settings, 'admin.hr-attendance') ||
    hasEmployeePermission(user, settings, 'admin.employees')
  );
}

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 (!canAccess(session.user, settings)) {
      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') || 100)));
    const status = url.searchParams.get('status') || undefined;
    const employeeId = url.searchParams.get('employeeId') || undefined;

    const result = await pgGetAttendanceCorrectionRequests({
      page,
      pageSize,
      status,
      employeeId,
    });

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