/**
 * Chunked Ticket Sync API Endpoint
 * POST /api/sync/tickets-chunked - Trigger chunked ticket sync with progress updates
 */

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { yearsBack = 2, triggeredBy = 'api' } = body;

    // Validate yearsBack
    if (typeof yearsBack !== 'number' || yearsBack <= 0) {
      return NextResponse.json(
        { error: 'yearsBack must be a positive number' },
        { status: 400 }
      );
    }

    // 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 entity sync service
    const entitySyncService = createEntitySyncService(autotaskClient);

    // Start chunked ticket sync (non-blocking)
    // Progress updates will be logged to console
    entitySyncService.syncTicketsChunked(yearsBack, (chunk) => {
      console.log(`[Chunked Sync Progress] ${chunk.description}: ${chunk.index}/${chunk.total} (${chunk.recordsProcessed} records)`);
    }).catch((error) => {
      console.error('Chunked ticket sync failed:', error);
    });

    return NextResponse.json({
      message: `Chunked ticket sync started for last ${yearsBack} years`,
      triggeredBy,
      yearsBack,
    });
  } catch (error) {
    console.error('Failed to start chunked ticket sync:', error);
    return NextResponse.json(
      { error: 'Failed to start chunked ticket sync' },
      { status: 500 }
    );
  }
}
