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 page = url.searchParams.get('page') || '1';
  const limit = url.searchParams.get('limit') || '20';
  const q = url.searchParams.get('q') || '';

  const upstreamUrl = `${BASE}/api/courses?page=${encodeURIComponent(page)}&pageSize=${encodeURIComponent(limit)}${q ? `&q=${encodeURIComponent(q)}` : ''}`;

  try {
    const res = await fetch(upstreamUrl, { headers: { Accept: 'application/json' } });
    if (!res.ok) {
      return NextResponse.json({ error: 'Upstream error', status: res.status }, { status: res.status });
    }
    const json = await res.json();
    return NextResponse.json({
      data: json.items || [],
      total: json.total ?? 0,
      page: json.page ?? Number(page),
      limit: json.pageSize ?? Number(limit),
      q,
    });
  } catch (err: any) {
    return NextResponse.json({ error: 'Failed to fetch upstream', message: err?.message }, { status: 502 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const payload = await req.json();
    const upstreamUrl = `${BASE}/api/courses`;
    const res = await fetch(upstreamUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify(payload),
    });
    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, { status: res.status });
  } catch (err: any) {
    return NextResponse.json({ error: 'Failed to fetch upstream', message: err?.message }, { status: 502 });
  }
}
