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

/**
 * Generic gateway proxy endpoint for admin panel
 * Forwards all requests to the Rust backend gateway with proper auth headers
 */
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 rawPath = `/${pathArray.join('/')}`.replace(/\/{2,}/g, '/');
    const path = normalizeGatewayPath(rawPath);
    const url = new URL(request.url);
    const queryString = url.search ? url.search : '';

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

    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);
    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' } },
    );
  }
}

function normalizeGatewayPath(rawPath: string): string {
  const clean = rawPath.replace(/\/{2,}/g, '/');

  // Legacy admin auth endpoints from Next.js build.
  if (/^\/(?:users\/)?auth\/internal\/login$/i.test(clean)) return '/api/auth/login';
  if (/^\/(?:users\/)?auth\/me$/i.test(clean)) return '/api/auth/session';
  if (/^\/(?:users\/)?auth\/logout$/i.test(clean)) return '/api/auth/logout';

  // Generic auth fallback: /auth/* or /users/auth/* => /api/auth/*
  const authFallback = clean.match(/^\/(?:users\/)?auth\/(.+)$/i);
  if (authFallback) return `/api/auth/${authFallback[1]}`;

  // Rust gateway routes are mounted under /api/*
  return clean.startsWith('/api/') ? clean : `/api${clean}`;
}
