import { NextRequest, NextResponse } from 'next/server';

const PLATFORM_SERVICE_URL = process.env.PLATFORM_SERVICE_URL || 'http://localhost:4003';
const PRODUCT_ID = process.env.PRODUCT_ID || 'unknown';

/**
 * Proxy admin self-telemetry events from the browser to platform-service.
 * Separate from /api/telemetry which is the admin query route for viewing client logs.
 * Accepts sendBeacon POST requests from the client-side telemetry module.
 */
export async function POST(req: NextRequest) {
  try {
    const body = await req.text();

    const res = await fetch(`${PLATFORM_SERVICE_URL}/api/telemetry/events`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Product-Id': PRODUCT_ID,
      },
      body,
    });

    if (res.ok) {
      return NextResponse.json({ ok: true });
    }
    return NextResponse.json({ ok: false }, { status: res.status });
  } catch {
    return NextResponse.json({ ok: false }, { status: 502 });
  }
}
