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 {
  pgDeactivateEmployeeBiometricMapping,
  pgGetEmployeeBiometricMappingById,
} 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 mapping = await pgGetEmployeeBiometricMappingById(id);
    if (!mapping) {
      return NextResponse.json({ error: 'Biometric mapping not found' }, { status: 404 });
    }

    if (!mapping.isActive) {
      return NextResponse.json({
        success: true,
        message: 'Mapping is already inactive',
      });
    }

    await pgDeactivateEmployeeBiometricMapping(id);

    return NextResponse.json({
      success: true,
      message: 'Biometric mapping deactivated successfully',
    });
  } catch (error) {
    console.error('Error deactivating biometric mapping:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
