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 { pgCreateBiometricDevice, pgGetBiometricDevices } 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 status = url.searchParams.get('status') || undefined;
    const providerType = url.searchParams.get('providerType') || undefined;
    const branchId = url.searchParams.get('branchId') || undefined;

    const result = await pgGetBiometricDevices({ page, pageSize, status, providerType, branchId });
    return NextResponse.json(result);
  } catch (error) {
    console.error('Error fetching biometric devices:', 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 {
      deviceId,
      deviceName,
      brand,
      model,
      serialNumber,
      ipAddress,
      port,
      communicationKey,
      branchId,
      timezone,
      providerType,
      syncMode,
      status,
      lastSyncAt,
      firmwareVersion,
    } = body as Record<string, any>;

    if (!deviceId || !deviceName || !serialNumber || !ipAddress || !providerType || !syncMode) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const created = await pgCreateBiometricDevice({
      deviceId: String(deviceId).trim(),
      deviceName: String(deviceName).trim(),
      brand: brand ? String(brand).trim() : undefined,
      model: model ? String(model).trim() : undefined,
      serialNumber: String(serialNumber).trim(),
      ipAddress: String(ipAddress).trim(),
      port: Number(port || 4370),
      communicationKey: communicationKey ? String(communicationKey).trim() : undefined,
      branchId: branchId ? String(branchId).trim() : undefined,
      timezone: timezone ? String(timezone).trim() : undefined,
      providerType: String(providerType).trim(),
      syncMode: syncMode === 'push' ? 'push' : 'pull',
      status: status || undefined,
      lastSyncAt: lastSyncAt || undefined,
      firmwareVersion: firmwareVersion ? String(firmwareVersion).trim() : undefined,
    });

    return NextResponse.json(created, { status: 201 });
  } catch (error: any) {
    if (error?.code === '23505') {
      return NextResponse.json({ error: 'Device identifier already exists' }, { status: 409 });
    }
    console.error('Error creating biometric device:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
