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 { pgCreateAttendanceDeviceLog, pgGetAttendanceDeviceLogs, 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 deviceId = url.searchParams.get('deviceId') || undefined;
    const employeeId = url.searchParams.get('employeeId') || undefined;
    const syncStatus = url.searchParams.get('syncStatus') || undefined;
    const fromDate = url.searchParams.get('fromDate') || undefined;
    const toDate = url.searchParams.get('toDate') || undefined;

    const [result, devices] = await Promise.all([
      pgGetAttendanceDeviceLogs({ page, pageSize, deviceId, employeeId, syncStatus, fromDate, toDate }),
      pgGetBiometricDevices({ page: 1, pageSize: 10000 }),
    ]);

    return NextResponse.json({
      ...result,
      devices: devices.items || [],
    });
  } catch (error) {
    console.error('Error fetching attendance device logs:', 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, enrollmentId, employeeId, logTime, rawPayload, processedRecordId, sourceType, punchType, syncStatus, duplicateKey, isDuplicate, manualAdjustment, manualAdjustedBy, manualAdjustmentReason, retryCount, auditTrail } = body as Record<string, any>;

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

    const created = await pgCreateAttendanceDeviceLog({
      deviceId: String(deviceId),
      enrollmentId: enrollmentId ? String(enrollmentId) : undefined,
      employeeId: employeeId ? String(employeeId) : undefined,
      logTime: String(logTime),
      rawPayload: rawPayload || undefined,
      processedRecordId: processedRecordId ? String(processedRecordId) : undefined,
      sourceType: sourceType ? String(sourceType) : undefined,
      punchType: punchType ? String(punchType) : undefined,
      syncStatus: syncStatus || undefined,
      duplicateKey: duplicateKey ? String(duplicateKey) : undefined,
      isDuplicate: isDuplicate === true,
      manualAdjustment: manualAdjustment === true,
      manualAdjustedBy: manualAdjustedBy ? String(manualAdjustedBy) : undefined,
      manualAdjustmentReason: manualAdjustmentReason ? String(manualAdjustmentReason) : undefined,
      retryCount: Number(retryCount || 0),
      auditTrail: auditTrail || undefined,
    });

    return NextResponse.json(created, { status: 201 });
  } catch (error) {
    console.error('Error creating attendance device log:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
