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

/** Read at request time so Docker runtime env vars are picked up (not inlined at build time). */
function getApiBaseUrl(): string {
  return process.env.API_BASE_URL || 'http://localhost:8000';
}

export async function GET(request: NextRequest, { params }: { params: { path: string[] } }) {
  return proxyRequest(request, params.path);
}

export async function POST(request: NextRequest, { params }: { params: { path: string[] } }) {
  return proxyRequest(request, params.path);
}

export async function PUT(request: NextRequest, { params }: { params: { path: string[] } }) {
  return proxyRequest(request, params.path);
}

export async function DELETE(request: NextRequest, { params }: { params: { path: string[] } }) {
  return proxyRequest(request, params.path);
}

async function proxyRequest(request: NextRequest, path: string[]) {
  const apiBase = getApiBaseUrl();
  const url = `${apiBase}/${path.join('/')}${request.nextUrl.search}`;

  const headers: Record<string, string> = {};
  request.headers.forEach((value, key) => {
    if (!['host', 'connection'].includes(key.toLowerCase())) {
      headers[key] = value;
    }
  });

  const body = request.method !== 'GET' ? await request.text() : undefined;

  try {
    const response = await fetch(url, {
      method: request.method,
      headers,
      body,
    });

    const data = await response.text();
    return new NextResponse(data, {
      status: response.status,
      headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
    });
  } catch (error) {
    console.error(`Failed to proxy ${url}`, error);
    return NextResponse.json({ error: 'Proxy error', detail: String(error) }, { status: 502 });
  }
}
