/**
 * Catch-all proxy to tracker-service.
 * Forwards all /api/tracker/* requests to the tracker backend.
 */

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

const TRACKER_API = process.env.PLATFORM_API_URL || 'http://localhost:4003';

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

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

  try {
    const headers: Record<string, string> = { 'Content-Type': 'application/json' };
    const auth = req.headers.get('authorization');
    if (auth) headers['Authorization'] = auth;

    // Read token from client-side header or cookie
    const tokenHeader = req.headers.get('x-tracker-token');
    if (tokenHeader && !auth) {
      headers['Authorization'] = `Bearer ${tokenHeader}`;
    }

    // Forward product switcher header so platform-service filters by product
    const productId = req.headers.get('x-product-id');
    if (productId) headers['x-product-id'] = productId;

    const fetchOptions: RequestInit = {
      method: req.method,
      headers,
    };

    if (req.method !== 'GET' && req.method !== 'HEAD') {
      const body = await req.text();
      if (body) fetchOptions.body = body;
    }

    const res = await fetch(url.toString(), fetchOptions);
    const data = await res.text();

    return new NextResponse(data, {
      status: res.status,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch {
    return NextResponse.json({ error: 'Tracker service unavailable' }, { status: 502 });
  }
}

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