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, { params }: { params: { courseId: string } }) {
  const { courseId } = params;
  const upstreamUrl = `${BASE}/api/courses/${encodeURIComponent(courseId)}`;
  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(json);
  } catch (err: any) {
    return NextResponse.json({ error: 'Failed to fetch upstream', message: err?.message }, { status: 502 });
  }
}

export async function PUT(req: NextRequest, { params }: { params: { courseId: string } }) {
  const { courseId } = params;
  try {
    const payload = await req.json();
    const upstreamUrl = `${BASE}/api/courses/${encodeURIComponent(courseId)}`;
    const res = await fetch(upstreamUrl, {
      method: 'PUT',
      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 });
  }
}

export async function DELETE(_req: NextRequest, { params }: { params: { courseId: string } }) {
  const { courseId } = params;
  const upstreamUrl = `${BASE}/api/courses/${encodeURIComponent(courseId)}`;
  try {
    const res = await fetch(upstreamUrl, {
      method: 'DELETE',
      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, { status: res.status });
  } catch (err: any) {
    return NextResponse.json({ error: 'Failed to fetch upstream', message: err?.message }, { status: 502 });
  }
}