import { NextRequest, NextResponse } from 'next/server';
import { DattoRMMSyncService } from '@/lib/services/datto-rmm-sync-service';

let syncServiceInstance: DattoRMMSyncService | null = null;

function getSyncService(): DattoRMMSyncService {
  if (!syncServiceInstance) {
    syncServiceInstance = new DattoRMMSyncService();
  }
  return syncServiceInstance;
}

export async function POST(request: NextRequest) {
  try {
    const syncService = getSyncService();

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

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

    const resultPromise = syncType === 'full'
      ? syncService.fullSync('manual')
      : syncService.incrementalSync('manual');

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

    return NextResponse.json({
      message: `Datto RMM ${syncType} sync started`,
      syncType,
    });
  } catch (error) {
    console.error('[DATTO-RMM-SYNC-API] Error:', error);
    return NextResponse.json(
      { error: 'Failed to start Datto RMM 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 }
    );
  }
}
