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

const API = process.env.NEXT_PUBLIC_API_URL ?? 'http://127.0.0.1:3000';

export async function GET(req: NextRequest) {
  const path = req.nextUrl.pathname.replace('/api/catalog-proxy/', '');
  const cookies = req.headers.get('cookie') ?? '';
  try {
    const res = await fetch(`${API}/${path}${req.nextUrl.search}`, {
      headers: { accept: 'application/json', cookie: cookies },
    });
    const data = await res.json().catch(() => ({}));
    return NextResponse.json(data, { status: res.status });
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 502 });
  }
}

export async function POST(req: NextRequest) {
  const path = req.nextUrl.pathname.replace('/api/catalog-proxy/', '');
  const cookies = req.headers.get('cookie') ?? '';
  const body = await req.text();
  try {
    const res = await fetch(`${API}/${path}${req.nextUrl.search}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', cookie: cookies },
      body,
    });
    const data = await res.json().catch(() => ({}));
    return NextResponse.json(data, { status: res.status });
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 502 });
  }
}
