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

let syncServiceInstance: VeeamSyncService | null = null;
function getSyncService(): VeeamSyncService {
  if (!syncServiceInstance) syncServiceInstance = new VeeamSyncService();
  return syncServiceInstance;
}

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

  try {
    const syncService = getSyncService();

    if (syncService.isSyncInProgress()) {
      return NextResponse.json({ error: 'A Veeam sync is already in progress' }, { status: 409 });
    }

    const body = await request.json().catch(() => ({}));
    const syncType = body.syncType === 'full' ? 'full' : 'incremental';

    (syncType === 'full'
      ? syncService.fullSync('openclaw')
      : syncService.incrementalSync('openclaw')
    ).catch((err) => console.error('[OpenClaw] Veeam sync failed:', err));

    return NextResponse.json({
      message: `Veeam ${syncType} sync started`,
      syncType,
      triggeredBy: 'openclaw',
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
