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

/**
 * POST /api/hr/attendance/clock-out-biometric
 * 
 * Receives check-out 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 }
      );
    }

    const checkOutTime = new Date(timestamp).toISOString();
    const dateStr = new Date(timestamp).toISOString().split('T')[0];

    // Find today's check-in record
    const todayRecords = await pgGetAttendanceRecords({
      page: 1,
      pageSize: 100,
      employeeId: biometricMapping.employeeId,
      fromDate: dateStr,
      toDate: dateStr,
    });

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

    if (!todayRecord || !todayRecord.check_in_time) {
      return NextResponse.json(
        { 
          error: 'No check-in record found for today',
          employeeId: biometricMapping.employeeId,
        },
        { status: 404 }
      );
    }

    if (todayRecord.check_out_time) {
      return NextResponse.json(
        { 
          error: 'Employee already checked out today',
          recordId: todayRecord.id,
          checkOutTime: todayRecord.check_out_time,
        },
        { status: 400 }
      );
    }

    // Calculate duration
    const checkInMs = new Date(todayRecord.check_in_time).getTime();
    const checkOutMs = new Date(checkOutTime).getTime();
    const durationHours = (checkOutMs - checkInMs) / (1000 * 60 * 60);

    // Update record with check-out
    const updatedRecord = await pgUpdateAttendanceRecord(
      todayRecord.id,
      {
        checkOutTime,
        durationHours: Math.round(durationHours * 100) / 100,
      },
      'biometric-device'
    );

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