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 {
  pgCreateEmployeeBiometricMapping,
  pgGetEmployeeBiometricByBiometricId,
  pgGetEmployeeBiometricByEmployeeId,
  pgGetEmployeeBiometricMappings,
} 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 isActiveRaw = url.searchParams.get('isActive');
    const isActive = isActiveRaw === null ? undefined : isActiveRaw === 'true';

    const [mappings, employees] = await Promise.all([
      pgGetEmployeeBiometricMappings({
        page,
        pageSize,
        employeeId,
        isActive,
      }),
      pgGetEmployees({ page: 1, pageSize: 10000 }),
    ]);

    return NextResponse.json({
      ...mappings,
      employees: employees.items || [],
    });
  } catch (error) {
    console.error('Error fetching biometric mappings:', 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,
      biometricId,
      deviceType,
      deviceMacAddress,
    } = body as {
      employeeId?: string;
      biometricId?: string;
      deviceType?: string;
      deviceMacAddress?: string;
    };

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

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

    const employeeName =
      employee.name ||
      employee.fullName ||
      employee.employeeName ||
      employee.arabicName ||
      employeeId;

    const existingEmployeeMapping = await pgGetEmployeeBiometricByEmployeeId(employeeId);
    if (existingEmployeeMapping?.isActive) {
      return NextResponse.json(
        { error: 'Employee already has an active biometric mapping' },
        { status: 409 }
      );
    }

    const existingBiometricMapping = await pgGetEmployeeBiometricByBiometricId(biometricId);
    if (existingBiometricMapping?.isActive) {
      return NextResponse.json(
        { error: 'Biometric ID is already mapped to another employee' },
        { status: 409 }
      );
    }

    const mapping = await pgCreateEmployeeBiometricMapping({
      employeeId,
      employeeName,
      biometricId,
      deviceType,
      deviceMacAddress,
      isActive: true,
    });

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