import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { getSentinelOneSyncService } from '@/lib/services/sentinelone-sync-service';

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

  try {
    const svc = getSentinelOneSyncService();

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

    svc.fullSync('openclaw').catch((err) => console.error('[OpenClaw] SentinelOne sync failed:', err));

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