import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';

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

  if (!process.env.ZABBIX_API_URL || !process.env.ZABBIX_API_TOKEN) {
    return NextResponse.json({ error: 'Zabbix not configured' }, { status: 503 });
  }

  try {
    const baseUrl = process.env.NEXT_PUBLIC_BETTER_AUTH_URL || 'http://localhost:3100';

    const [hostsRes, eventsRes] = await Promise.all([
      fetch(`${baseUrl}/api/zabbix/sync-hosts`, { method: 'POST' }),
      fetch(`${baseUrl}/api/zabbix/sync-events`, { method: 'POST' }),
    ]);

    const [hosts, events] = await Promise.all([
      hostsRes.json().catch(() => ({})),
      eventsRes.json().catch(() => ({})),
    ]);

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