import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
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) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

  try {
    const body = await request.json();
    const { entities, yearsBack } = body;

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

    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 });
      }
    }

    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 || '',
    });

    const syncService = createSyncService(autotaskClient);

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

    syncService.syncEntities(validEntities, 'entity-specific' as SyncType, 'openclaw', yearsBack).catch((err) => {
      console.error('[OpenClaw] Autotask entity sync failed:', err);
    });

    return NextResponse.json({
      message: `Autotask entity sync started for: ${validEntities.join(', ')}`,
      syncId: syncService.getCurrentSyncId(),
      entities: validEntities,
      triggeredBy: 'openclaw',
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
