import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { getZoomSyncService } from '@/lib/services/zoom-sync-service';
import { isZoomConfigured } from '@/lib/services/zoom-factory';

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

  if (!isZoomConfigured()) {
    return NextResponse.json({ error: 'Zoom credentials not configured' }, { status: 503 });
  }

  try {
    const service = getZoomSyncService();

    if (service.isSyncInProgress()) {
      return NextResponse.json({ error: 'Zoom sync already in progress' }, { status: 409 });
    }

    service.sync().catch((err) => console.error('[OpenClaw] Zoom sync failed:', err));

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