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

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

const HANDLERS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const;

export async function GET(req: NextRequest) { return handle(req); }
export async function POST(req: NextRequest) { return handle(req); }
export async function PUT(req: NextRequest) { return handle(req); }
export async function PATCH(req: NextRequest) { return handle(req); }
export async function DELETE(req: NextRequest) { return handle(req); }

async function handle(req: NextRequest): Promise<NextResponse> {
  const path = req.nextUrl.pathname.replace('/api/catalog-proxy/', '');
  const url = `${API}/${path}${req.nextUrl.search}`;
  const headers: Record<string, string> = { accept: 'application/json' };
  const cookie = req.headers.get('cookie');
  if (cookie) headers.cookie = cookie;

  const init: RequestInit = { headers };
  if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
    init.method = req.method;
    init.body = await req.text();
    const ct = req.headers.get('content-type');
    if (ct) headers['content-type'] = ct;
  }

  try {
    const res = await fetch(url, init);
    const data = await res.json().catch(() => ({}));
    const setCookie = res.headers.get('set-cookie');
    if (setCookie) {
      return NextResponse.json(data, { status: res.status, headers: { 'set-cookie': setCookie } });
    }
    return NextResponse.json(data, { status: res.status });
  } catch (err) {
    return NextResponse.json({ error: { code: 'PROXY_ERROR', message: String(err) } }, { status: 502 });
  }
}
