/**
 * Entity-Specific Sync API Endpoint
 * POST /api/sync/entity - Trigger sync for specific entities
 */

import { NextRequest, NextResponse } from 'next/server';
import { AutotaskClient } from '@/lib/services/autotask-client';
import { createSyncService } from '@/lib/services/sync-service';
import { EntityType, SyncType } from '@/lib/types/sync';
import { isValidEntityType } from '@/lib/utils/sync-helpers';

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

    // Validate entities
    if (!entities || !Array.isArray(entities) || entities.length === 0) {
      return NextResponse.json(
        { error: 'entities array is required' },
        { status: 400 }
      );
    }

    // Validate each entity type
    const validEntities: EntityType[] = [];
    for (const entity of entities) {
      if (isValidEntityType(entity)) {
        validEntities.push(entity as EntityType);
      } else {
        return NextResponse.json(
          { error: `Invalid entity type: ${entity}` },
          { 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 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 entity sync (non-blocking)
    syncService.syncEntities(validEntities, syncType as SyncType, triggeredBy, yearsBack).catch((error) => {
      console.error('Entity sync failed:', error);
    });

    return NextResponse.json({
      message: `Sync started for ${validEntities.length} entities`,
      syncId: syncService.getCurrentSyncId(),
      entities: validEntities,
    });
  } catch (error) {
    console.error('Failed to start entity sync:', error);
    return NextResponse.json(
      { error: 'Failed to start entity sync' },
      { status: 500 }
    );
  }
}
