// src/lib/api-utils.ts
import { NextRequest, NextResponse } from 'next/server';

export async function proxyRequest(
  request: NextRequest,
  path: string,
  method?: string,
  timeout: number = 60000 // Default timeout of 60 seconds
) {
  try {
    const apiUrl = process.env.BACKEND_URL || 'http://your-backend-api';
    const url = new URL(path, apiUrl);
    
    // Copy query parameters
    const requestUrl = new URL(request.url);
    requestUrl.searchParams.forEach((value, key) => {
      url.searchParams.append(key, value);
    });
    
    // Prepare request options
    const options: RequestInit = {
      method: method || request.method,
      headers: {
        'Content-Type': 'application/json',
      },
      signal: AbortSignal.timeout(timeout), // Set timeout for the request
    };
    
    // Copy authorization headers if present
    const authHeader = request.headers.get('Authorization');
    if (authHeader) {
      options.headers = {
        ...options.headers,
        'Authorization': authHeader,
      };
    }
    
    // Handle request body for methods that support it
    if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(options.method || '')) {
      try {
        const body = await request.json();
        options.body = JSON.stringify(body);
      } catch (e) {
        // No body or invalid JSON
      }
    }
    
    console.log(`Proxying ${options.method} request to: ${url.toString()}`);
    
    const response = await fetch(url, options);
    
    // Handle different response types
    const contentType = response.headers.get('content-type');
    
    if (contentType?.includes('application/json')) {
      const data = await response.json();
      return NextResponse.json(data, { status: response.status });
    } else {
      const text = await response.text();
      return new NextResponse(text, {
        status: response.status,
        headers: {
          'Content-Type': contentType || 'text/plain',
        },
      });
    }
  } catch (error) {
    console.error('API proxy error:', error);
    
    // Check if it's a timeout error
    if (error instanceof DOMException && error.name === 'AbortError') {
      return NextResponse.json(
        { error: 'Request timeout', message: 'The request took too long to complete' },
        { status: 504 }
      );
    }
    
    return NextResponse.json(
      { error: 'Internal Server Error', message: (error as Error).message },
      { status: 500 }
    );
  }
}
