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

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

/** PATCH /api/cart/items/[variantId] -> backend PATCH /cart/items/:variantId */
export async function PATCH(
  req: NextRequest,
  ctx: { params: Promise<{ variantId: string }> },
) {
  const { variantId } = await ctx.params;
  const body = await req.text();
  const cookies = req.headers.get('cookie') ?? '';
  try {
    const backendRes = await fetch(`${API}/cart/items/${encodeURIComponent(variantId)}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json', 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 DELETE(
  req: NextRequest,
  ctx: { params: Promise<{ variantId: string }> },
) {
  const { variantId } = await ctx.params;
  const cookies = req.headers.get('cookie') ?? '';
  try {
    const backendRes = await fetch(`${API}/cart/items/${encodeURIComponent(variantId)}`, {
      method: 'DELETE',
      headers: { Cookie: cookies },
    });
    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 });
  }
}