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

function canManageAttendance(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 (!canManageAttendance(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') || 50)));
    const employeeId = url.searchParams.get('employeeId') || undefined;
    const deviceId = url.searchParams.get('deviceId') || undefined;
    const enrollmentStatus = url.searchParams.get('enrollmentStatus') || undefined;

    const [result, employees, devices] = await Promise.all([
      pgGetBiometricEnrollments({ page, pageSize, employeeId, deviceId, enrollmentStatus }),
      pgGetEmployees({ page: 1, pageSize: 10000 }),
      pgGetBiometricDevices({ page: 1, pageSize: 10000 }),
    ]);

    return NextResponse.json({
      ...result,
      employees: employees.items || [],
      devices: devices.items || [],
    });
  } catch (error) {
    console.error('Error fetching enrollment 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 (!canManageAttendance(session.user, settings)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await request.json();
    const { employeeId, deviceId, biometricUserId, cardNumber, enrollmentStatus, enrolledAt } = body as Record<string, any>;

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

    const created = await pgCreateBiometricEnrollment({
      employeeId: String(employeeId),
      deviceId: String(deviceId),
      biometricUserId: String(biometricUserId),
      cardNumber: cardNumber ? String(cardNumber) : undefined,
      enrollmentStatus: enrollmentStatus || undefined,
      enrolledAt: enrolledAt || undefined,
    });

    return NextResponse.json(created, { status: 201 });
  } catch (error: any) {
    if (error?.code === '23505') {
      return NextResponse.json({ error: 'Enrollment already exists for this device user/card' }, { status: 409 });
    }
    console.error('Error creating enrollment:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
