/**
 * Full Sync API Endpoint
 * POST /api/sync/full - Trigger a full sync of all entities
 */

import { NextRequest, NextResponse } from 'next/server';
import { AutotaskClient } from '@/lib/services/autotask-client';
import { createSyncService } from '@/lib/services/sync-service';

export async function POST(request: NextRequest) {
  try {
    // Get triggered by from request body
    const body = await request.json().catch(() => ({}));
    const triggeredBy = body.triggeredBy || 'api';
    const yearsBack = body.yearsBack;

    // Initialize Autotask client
    const autotaskClient = new AutotaskClient({
      apiUrl: process.env.AUTOTASK_API_URL || '',
      username: process.env.AUTOTASK_USERNAME || '',
      password: process.env.AUTOTASK_SECRET || '',
      apiIntegrationCode: process.env.AUTOTASK_API_INTEGRATION_CODE || '',
    });

    // Create sync service
    const syncService = createSyncService(autotaskClient);

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

    // Start full sync (non-blocking)
    syncService.fullSync(triggeredBy, yearsBack).catch((error) => {
      console.error('Full sync failed:', error);
    });

    return NextResponse.json({
      message: 'Full sync started',
      syncId: syncService.getCurrentSyncId(),
    });
  } catch (error) {
    console.error('Failed to start full sync:', error);
    return NextResponse.json(
      { error: 'Failed to start full sync' },
      { status: 500 }
    );
  }
}
