import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const endpoint = searchParams.get('endpoint');
  const proxyUrl = process.env.NEXT_PUBLIC_PO_API_URL || '';
  const apiKey = process.env.NEXT_PUBLIC_PO_API_KEY || '';

  if (!endpoint || !proxyUrl) {
    return NextResponse.json({ error: 'Missing configuration' }, { status: 400 });
  }

  // Construct target URL
  // endpoint passed like: /purchase-orders?supplier_id=1...
  // ensure no double slashes
  // Also encode URI to handle spaces if they leaked through
  const cleanBase = proxyUrl.replace(/\/$/, '');
  const cleanEndpoint = endpoint.replace(/^\//, '');
  
  let targetUrl: string;
  try {
    // Use URL constructor to automatically encode spaces/special chars in query params
    const urlObj = new URL(`${cleanBase}/${cleanEndpoint}`);
    targetUrl = urlObj.toString();
  } catch (e) {
    // Fallback if URL construction fails (unlikely if base is valid)
    console.warn('URL construction failed, falling back to string concat', e);
    targetUrl = `${cleanBase}/${cleanEndpoint}`; 
  }
  
  console.log(`Proxying request to: ${targetUrl}`);

  try {
    const response = await fetch(targetUrl, {
      headers: {
        'X-API-Key': apiKey,
        'Accept': 'application/json',
        'ngrok-skip-browser-warning': 'true', // Still needed for ngrok, but server-to-server is fine
        'User-Agent': 'Monrita-NextJS-Proxy/1.0'
      },
      cache: 'no-store',
    });

    if (!response.ok) {
       const text = await response.text();
       console.error(`Upstream API Error (${response.status}):`, text);
       try {
          return NextResponse.json(JSON.parse(text), { status: response.status });
       } catch (e) {
          return NextResponse.json({ error: 'Upstream Error', details: text }, { status: response.status });
       }
    }

    const data = await response.json();
    return NextResponse.json(data, { status: response.status });

  } catch (error: any) {
    console.error('Proxy Connection Error:', error);
    return NextResponse.json({ 
        error: 'Proxy failed', 
        details: error.message, 
        target: targetUrl,
        cause: error.cause 
    }, { status: 502 });
  }
}
