import { NextResponse } from 'next/server';
import '@/lib/shopware-server-init';
import {
  getCart,
  getContext,
  getShippingMethods,
} from '@/lib/shopware-api';

export const dynamic = 'force-dynamic';

/**
 * Diagnostic: dumps the current cart's delivery shipping costs, the active
 * context shipping method, and every shipping method's configured price.
 * Hit /api/debug-cart in the browser while logged in / with an active cart.
 */
export async function GET() {
  const out: Record<string, any> = {};

  try {
    const cart = await getCart();
    out.cart_price = cart?.price ?? null;
    out.deliveries = (cart?.deliveries as any[])?.map((d) => ({
      shippingCosts: d?.shippingCosts ?? null,
      shippingMethod: d?.shippingMethod
        ? { id: d.shippingMethod.id, name: d.shippingMethod.name }
        : null,
    })) ?? null;
  } catch (e: any) {
    out.cart_error = e?.message ?? String(e);
  }

  try {
    const ctx = await getContext();
    out.active_shipping_method = ctx?.shippingMethod
      ? { id: ctx.shippingMethod.id, name: ctx.shippingMethod.name }
      : null;
  } catch (e: any) {
    out.context_error = e?.message ?? String(e);
  }

  try {
    const methods = await getShippingMethods();
    out.shipping_methods = (methods.elements ?? []).map((m: any) => ({
      id: m.id,
      name: m.name,
      prices: m.prices,
    }));
  } catch (e: any) {
    out.shipping_methods_error = e?.message ?? String(e);
  }

  return NextResponse.json(out, { status: 200 });
}
