import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { duoSyncService } from '@/lib/services/duo-sync-service';

export async function POST(request: NextRequest) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

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

    duoSyncService.syncAll('openclaw').catch(err => {
      console.error('[DuoSync] Background sync error (openclaw):', err);
    });

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