import { NextRequest, NextResponse } from 'next/server';
import {
  pgGetEmployeeBiometricByBiometricId,
  pgGetAttendanceRecords,
  pgCreateAttendanceRecord,
  pgUpdateAttendanceRecord,
} from '@/lib/postgres/attendance';

/**
 * POST /api/hr/attendance/clock-in-biometric
 * 
 * Receives check-in from biometric device
 * Body: {
 *   biometricId: string,
 *   timestamp: ISO string,
 *   deviceId: string,
 *   deviceMacAddress: string
 * }
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { biometricId, timestamp, deviceId, deviceMacAddress } = body;

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

    // Find employee by biometric ID
    const biometricMapping = await pgGetEmployeeBiometricByBiometricId(biometricId);
    if (!biometricMapping) {
      return NextResponse.json(
        { error: 'Biometric ID not found in system' },
        { status: 404 }
      );
    }

    // Verify MAC address if provided
    if (deviceMacAddress && biometricMapping.deviceMacAddress && biometricMapping.deviceMacAddress !== deviceMacAddress) {
      console.warn(`MAC address mismatch for biometric ${biometricId}`);
      // Continue anyway - just log the warning
    }

    const checkInTime = new Date(timestamp).toISOString();
    const dateStr = new Date(timestamp).toISOString().split('T')[0];
    const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip');

    // Check if already checked in today
    const todayRecords = await pgGetAttendanceRecords({
      page: 1,
      pageSize: 100,
      employeeId: biometricMapping.employeeId,
      fromDate: dateStr,
      toDate: dateStr,
    });

    const todayRecord = todayRecords.items?.[0];

    if (todayRecord) {
      if (todayRecord.check_in_time && !todayRecord.check_out_time) {
        // Already checked in - maybe this is a check-out attempt?
        return NextResponse.json(
          { 
            error: 'Employee already checked in today',
            recordId: todayRecord.id,
            checkInTime: todayRecord.check_in_time,
          },
          { status: 400 }
        );
      }
    }

    // Create check-in record
    const record = await pgCreateAttendanceRecord({
      employeeId: biometricMapping.employeeId,
      date: dateStr,
      recordType: 'present',
      checkInTime,
      device: 'biometric',
      deviceId: biometricId,
      ipAddress: ipAddress || undefined,
      status: 'approved', // Auto-approve biometric check-ins
      createdBy: 'biometric-device',
    });

    return NextResponse.json({
      success: true,
      message: `Check-in recorded for ${biometricMapping.employeeName}`,
      recordId: record.id,
      employeeId: biometricMapping.employeeId,
      employeeName: biometricMapping.employeeName,
      checkInTime,
    });
  } catch (error) {
    console.error('Error processing biometric check-in:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
