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';

export async function POST(request: NextRequest) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

  try {
    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.incrementalSync('openclaw').catch((err) => {
      console.error('[OpenClaw] Autotask incremental sync failed:', err);
    });

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