/**
 * External webhook ingestion proxy.
 *
 * Keeps tracker-web's public webhook URLs stable while platform-service handles
 * signature validation, event parsing, item/PR linking, and persistence.
 */

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

const PLATFORM_API = process.env.PLATFORM_API_URL || 'http://localhost:4003';
const FORWARDED_HEADERS = [
  'authorization',
  'content-type',
  'x-product-id',
  'x-hub-signature',
  'x-hub-signature-256',
  'x-github-event',
  'x-gitea-event',
  'x-gitlab-event',
  'x-webhook-signature',
  'x-webhook-timestamp',
];

async function proxy(req: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params;
  const url = new URL(`/api/webhooks/${path.join('/')}`, PLATFORM_API);

  req.nextUrl.searchParams.forEach((value, key) => {
    url.searchParams.set(key, value);
  });

  try {
    const headers: Record<string, string> = {};
    for (const key of FORWARDED_HEADERS) {
      const value = req.headers.get(key);
      if (value) headers[key] = value;
    }
    if (!headers['content-type']) headers['content-type'] = 'application/json';

    const body = await req.text();
    const res = await fetch(url.toString(), {
      method: req.method,
      headers,
      body,
    });
    const data = await res.text();

    return new NextResponse(data, {
      status: res.status,
      headers: { 'Content-Type': res.headers?.get('content-type') || 'application/json' },
    });
  } catch {
    return NextResponse.json({ error: 'Webhook ingestion unavailable' }, { status: 502 });
  }
}

export const POST = proxy;
export const PUT = proxy;
export const PATCH = proxy;
