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 { pgGetBiometricEnrollmentById, pgUpdateBiometricEnrollmentStatus } 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 POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  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 { id } = await params;
    const enrollment = await pgGetBiometricEnrollmentById(id);
    if (!enrollment) return NextResponse.json({ error: 'Enrollment not found' }, { status: 404 });

    const body = await request.json();
    const status = String(body?.status || '').trim();
    if (!['active', 'pending', 'suspended', 'revoked'].includes(status)) {
      return NextResponse.json({ error: 'Invalid status' }, { status: 400 });
    }

    const updated = await pgUpdateBiometricEnrollmentStatus(id, status as any);
    return NextResponse.json({ success: true, enrollment: updated });
  } catch (error) {
    console.error('Error updating enrollment status:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
