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

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

async function proxy(req: NextRequest, method: 'GET' | 'POST', path: string) {
  const cookies = req.headers.get('cookie') ?? '';
  let body: string | undefined;
  if (method === 'POST') body = await req.text();
  try {
    const backendRes = await fetch(`${API}${path}`, {
      method,
      headers: {
        'Content-Type': 'application/json',
        ...(cookies ? { Cookie: cookies } : {}),
      },
      body,
    });
    const data = await backendRes.json().catch(() => null);
    return NextResponse.json(data ?? { error: 'Bad response' }, { status: backendRes.status });
  } catch {
    return NextResponse.json({ error: 'Proxy error' }, { status: 502 });
  }
}

export async function GET(req: NextRequest) {
  return proxy(req, 'GET', '/cart');
}

export async function POST(req: NextRequest) {
  return proxy(req, 'POST', '/cart/items');
}