/**
 * Catch-all proxy to platform-service fleet endpoints.
 * Forwards all /api/fleet/* requests to the fleet backend.
 */

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

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

async function proxy(req: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params;
  // platform-service mounts fleet routes under the /api prefix.
  const targetPath = `/api/fleet/${path.join('/')}`;
  const url = new URL(targetPath, PLATFORM_API);

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

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

    const tokenHeader = req.headers.get('x-tracker-token');
    if (tokenHeader && !auth) {
      headers['Authorization'] = `Bearer ${tokenHeader}`;
    }

    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;
        // Only declare a JSON body when there actually is one — bodyless POSTs
        // (operator actions: ship/requeue/cancel) must NOT send Content-Type, or
        // the backend rejects them with FST_ERR_CTP_EMPTY_JSON_BODY.
        headers['Content-Type'] = 'application/json';
      }
    }

    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: 'Fleet service unavailable' }, { status: 502 });
  }
}

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