import { gatewayUrl, withAuthHeaders } from '~/lib/server/gateway';

/**
 * Generic gateway proxy endpoint
 * Forwards all requests to the Rust backend gateway with proper auth headers
 * Usage: /api/gateway/api/companies/jobs → forwards to gateway /api/companies/jobs
 */
export async function GET({ request, params }: { request: Request; params: any }) {
  return proxyRequest('GET', request, params);
}

export async function POST({ request, params }: { request: Request; params: any }) {
  return proxyRequest('POST', request, params);
}

export async function PUT({ request, params }: { request: Request; params: any }) {
  return proxyRequest('PUT', request, params);
}

export async function DELETE({ request, params }: { request: Request; params: any }) {
  return proxyRequest('DELETE', request, params);
}

export async function PATCH({ request, params }: { request: Request; params: any }) {
  return proxyRequest('PATCH', request, params);
}

async function proxyRequest(method: string, request: Request, params: any) {
  try {
    // Handle different param structures
    let pathArray = params.path;
    if (!Array.isArray(pathArray)) {
      pathArray = [pathArray];
    }
    
    const path = `/${pathArray.join('/')}`;

    // Preserve query string
    const url = new URL(request.url);
    const queryString = url.search ? url.search : '';

    // Build request body if needed
    let body: string | undefined;
    if (['POST', 'PUT', 'PATCH'].includes(method)) {
      body = await request.text();
    }

    // Forward to gateway
    const upstreamUrl = gatewayUrl(path + queryString);
    const upstreamRequest = new Request(upstreamUrl, {
      method,
      headers: withAuthHeaders(request, {
        'Content-Type': request.headers.get('Content-Type') || 'application/json',
      }),
      body,
      cache: 'no-store',
    });

    const response = await fetch(upstreamRequest);

    // Copy response headers and return
    const responseHeaders = new Headers();
    response.headers.forEach((value, key) => {
      if (!['server', 'transfer-encoding', 'connection'].includes(key.toLowerCase())) {
        responseHeaders.set(key, value);
      }
    });
    responseHeaders.set('Content-Type', 'application/json');

    const responseBody = await response.text();

    return new Response(responseBody, {
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders,
    });
  } catch (error: any) {
    return new Response(
      JSON.stringify({ success: false, error: error?.message || 'Internal Server Error' }),
      { status: 500, headers: { 'Content-Type': 'application/json' } },
    );
  }
}
