import { NextRequest, NextResponse } from 'next/server';
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) {
  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';

    // Run sync in background, return immediately
    const resultPromise = syncType === 'full'
      ? syncService.fullSync('manual')
      : syncService.incrementalSync('manual');

    resultPromise.catch((err) => {
      console.error('[VEEAM-SYNC-API] Background sync failed:', err);
    });

    return NextResponse.json({
      message: `Veeam ${syncType} sync started`,
      syncType,
    });
  } catch (error) {
    console.error('[VEEAM-SYNC-API] Error:', error);
    return NextResponse.json(
      { error: 'Failed to start Veeam sync' },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    const syncService = getSyncService();
    return NextResponse.json({
      isSyncing: syncService.isSyncInProgress(),
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to get sync status' },
      { status: 500 }
    );
  }
}
