import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { getEngagementSyncService } from '@/lib/services/engagement-sync-service';
import { isMsgraphConfigured } from '@/lib/services/msgraph-factory';

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

  if (!isMsgraphConfigured()) {
    return NextResponse.json(
      { error: 'Microsoft Graph not configured. Set MSGRAPH_CLIENT_ID, MSGRAPH_CLIENT_SECRET, MSGRAPH_TENANT_ID.' },
      { status: 503 }
    );
  }

  try {
    const service = getEngagementSyncService();

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

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

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