import { NextResponse } from "next/server";
import type { CartItem } from "../../../lib/cart";
import { getServerCart, getSessionCustomer, saveServerCart } from "../../../lib/customerAuth";
import { fetchProductsBySlug } from "../../../lib/productsServer";

export async function GET() {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ cart: [] }, { status: 401 });
  const cart = await getServerCart(session.token);
  return NextResponse.json({ cart });
}

// Called by CartSync.tsx (debounced) on every local cart change while a
// session is active — keeps the server-side mirror current so the cart
// follows the customer across devices. Silently no-ops when logged out;
// the caller doesn't care either way.
export async function POST(request: Request) {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false }, { status: 401 });

  const body = await request.json().catch(() => null);
  const cart: CartItem[] = Array.isArray(body?.cart) ? body.cart : [];

  const productsBySlug = await fetchProductsBySlug();
  const lines: { productId: number; productSlug: string; quantity: number; variant?: string }[] = [];
  for (const item of cart) {
    const product = productsBySlug.get(item.id);
    if (product) lines.push({ productId: product.id, productSlug: product.slug, quantity: item.qty, variant: item.variant });
  }

  const ok = await saveServerCart(session.token, session.customer.id, lines);
  return NextResponse.json({ ok });
}
