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

// This catch-all API route proxies all /api/* requests to the backend
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return proxyToBackend(request, path);
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return proxyToBackend(request, path);
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return proxyToBackend(request, path);
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  return proxyToBackend(request, path);
}

async function proxyToBackend(request: NextRequest, pathSegments: string[]) {
  const path = pathSegments.join('/');
  // Use dedicated backend subdomain for reliable API access
  // The catch-all route strips '/api/' from the path, so we need to add it back
  const backendUrl = `https://files.mad-lawsuit.org/api/${path}`;
  
  // Get the search params from the original request
  const searchParams = request.nextUrl.searchParams.toString();
  const url = searchParams ? `${backendUrl}?${searchParams}` : backendUrl;

  try {
    // Forward the request to the backend
    const headers: HeadersInit = {};
    
    // Copy relevant headers
    request.headers.forEach((value, key) => {
      if (!key.startsWith('host') && !key.startsWith('connection')) {
        headers[key] = value;
      }
    });

    const options: RequestInit = {
      method: request.method,
      headers,
    };

    // Add body for POST, PUT, PATCH requests
    if (['POST', 'PUT', 'PATCH'].includes(request.method)) {
      const contentType = request.headers.get('content-type');
      if (contentType?.includes('application/json')) {
        options.body = JSON.stringify(await request.json());
      } else if (contentType?.includes('multipart/form-data')) {
        options.body = await request.formData();
      } else {
        options.body = await request.text();
      }
    }

    const response = await fetch(url, options);
    
    // Check if this is a file download (binary response)
    const contentType = response.headers.get('content-type') || '';
    const isFileDownload = contentType.includes('application/pdf') || 
                          contentType.includes('application/octet-stream') ||
                          response.headers.get('content-disposition');
    
    // Handle binary file downloads differently
    if (isFileDownload) {
      const blob = await response.blob();
      const headers = new Headers();
      
      // Copy important headers for file downloads
      if (response.headers.get('content-type')) {
        headers.set('Content-Type', response.headers.get('content-type')!);
      }
      if (response.headers.get('content-disposition')) {
        headers.set('Content-Disposition', response.headers.get('content-disposition')!);
      }
      if (response.headers.get('content-length')) {
        headers.set('Content-Length', response.headers.get('content-length')!);
      }
      
      return new NextResponse(blob, {
        status: response.status,
        headers,
      });
    }
    
    // Handle regular JSON/text responses
    const data = await response.text();
    
    return new NextResponse(data, {
      status: response.status,
      headers: {
        'Content-Type': contentType || 'application/json',
      },
    });
  } catch (error) {
    console.error('Proxy error:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to connect to backend' },
      { status: 500 }
    );
  }
}
