import { NextResponse } from 'next/server';
import { duoSyncService } from '@/lib/services/duo-sync-service';

export async function POST() {
  try {
    if (duoSyncService.isSyncInProgress()) {
      return NextResponse.json(
        { message: 'Duo sync already in progress', syncId: duoSyncService.getCurrentSyncId() },
        { status: 409 },
      );
    }

    // Fire-and-forget — don't await
    const syncId = `duo_sync_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
    duoSyncService.syncAll('api').catch(err => {
      console.error('[DuoSync] Background sync error:', err);
    });

    return NextResponse.json({ message: 'Duo sync started', syncId });
  } catch (error: any) {
    console.error('[DuoSync] Error starting sync:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function GET() {
  return NextResponse.json({
    inProgress: duoSyncService.isSyncInProgress(),
    currentSyncId: duoSyncService.getCurrentSyncId(),
  });
}
