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 telemetry events from the browser client to platform-service.
 * Accepts sendBeacon POST requests from the client-side telemetry module.
 */
export async function POST(req: NextRequest) {
  try {
    const body = await req.text();

    // The backend telemetry ingest requires a JWT or an X-Install-Token. Browser
    // beacons can't set an Authorization header, so derive an install token from
    // the payload (installId) with a stable fallback to satisfy the auth gate.
    let installToken = 'web-telemetry';
    try {
      const parsed = JSON.parse(body);
      installToken = parsed.installId || parsed.events?.[0]?.installId || installToken;
    } catch {
      /* keep fallback */
    }

    const res = await fetch(`${PLATFORM_SERVICE_URL}/api/telemetry/events`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Product-Id': PRODUCT_ID,
        'X-Install-Token': installToken,
      },
      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 });
  }
}
