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

const BASE = process.env.BACKEND_API_BASE_URL || process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8001';

export async function GET(req: NextRequest) {
  const url = new URL(req.url);
  const q = url.searchParams.get('q') || '';
  const upstreamUrl = `${BASE}/api/instructors${q ? `?q=${encodeURIComponent(q)}` : ''}`;
  try {
    const res = await fetch(upstreamUrl, { headers: { Accept: 'application/json' } });
    const text = await res.text();
    let json: any = null;
    try { json = JSON.parse(text); } catch { json = { raw: text }; }
    if (!res.ok) return NextResponse.json({ error: 'Upstream error', status: res.status, data: json }, { status: res.status });
    return NextResponse.json(json);
  } catch (err: any) {
    return NextResponse.json({ error: 'Failed to fetch upstream', message: err?.message }, { status: 502 });
  }
}