import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  // External Allocation API (supports search by school name, PO ID, supplier, commodity)
  const apiBase = process.env.ALLOCATION_API_URL || 'http://188.166.159.42:8012/api';
  const apiKey = process.env.ALLOCATION_API_KEY || '7hQ6anH7qVbWYPeglGDNw_ByE1cw88K33Yna42JCX4w';

  if (!apiBase) {
    return NextResponse.json({ error: 'Missing ALLOCATION_API_URL' }, { status: 500 });
  }

  const requestUrl = new URL(request.url);
  // External API uses /allocations/ endpoint (not /v1/purchase-orders/allocations)
  const targetUrl = new URL(`${apiBase.replace(/\/$/, '')}/allocations/`);

  requestUrl.searchParams.forEach((value, key) => {
    targetUrl.searchParams.set(key, value);
  });

  try {
    const response = await fetch(targetUrl.toString(), {
      headers: {
        ...(apiKey ? { 'X-API-Key': apiKey } : {}),
        'Accept': 'application/json',
        'User-Agent': 'Monrita-NextJS-Proxy/1.0'
      },
    });

    const text = await response.text();
    const contentType = response.headers.get('content-type') || '';

    if (!response.ok) {
      if (contentType.includes('application/json')) {
        return NextResponse.json(JSON.parse(text), { status: response.status });
      }
      return NextResponse.json({ error: 'Upstream Error', details: text }, { status: response.status });
    }

    if (contentType.includes('application/json')) {
      return NextResponse.json(JSON.parse(text), { status: response.status });
    }

    return new NextResponse(text, { status: response.status, headers: { 'Content-Type': contentType } });
  } catch (error: any) {
    return NextResponse.json({
      error: 'Proxy failed',
      details: error.message,
      target: targetUrl.toString(),
    }, { status: 502 });
  }
}
