import { NextResponse } from "next/server";
import {
  applyCartSessionCookies,
  getCartSessionFromRequestCookies,
  getRawStorefrontCart,
  normalizeStorefrontCart,
} from "@/lib/storefront-cart";

export async function GET() {
  try {
    const session = await getCartSessionFromRequestCookies();
    const result = await getRawStorefrontCart(session);
    const cart = await normalizeStorefrontCart(result.payload);
    const response = NextResponse.json(cart, {
      headers: {
        "Cache-Control": "private, no-store, max-age=0",
      },
    });

    applyCartSessionCookies(response, result.session);

    return response;
  } catch (error) {
    return NextResponse.json(
      {
        message: error instanceof Error ? error.message : "Cart request failed.",
      },
      { status: 500 },
    );
  }
}
