export const prerender = false;

import type { APIRoute } from 'astro';
import { env } from 'cloudflare:workers';
import { getSession, type SessionEnv } from '../../../lib/session.js';
import { getDb, type DbEnv } from '../../../lib/db.js';
import { createStorefrontCartStore } from '../../../lib/cart-store.js';
import { jsonOk } from '../../../lib/http.js';
import { type AuthEnv } from '../../../lib/auth-engine.js';
import { type StorefrontLimiterEnv } from '../../../lib/rate-limit.js';

const EMPTY_CART = { id: null, lines: [], subtotal: 0 };

function serializeCart(cart: Awaited<ReturnType<ReturnType<typeof createStorefrontCartStore>['load']>>) {
  if (!cart) return EMPTY_CART;
  return {
    id: cart.id,
    currency: cart.currency,
    subtotal: cart.subtotal.toString(),
    lines: cart.lines.map((l) => ({
      ...l,
      price: {
        ...l.price,
        amount: l.price.amount.toString(),
      },
    })),
  };
}

export const GET: APIRoute = async ({ cookies }) => {
  const cfEnv = env as (AuthEnv & SessionEnv & DbEnv & StorefrontLimiterEnv) | undefined;

  const session = cfEnv ? await getSession(cfEnv, cookies) : null;
  if (!session || !cfEnv?.DB && !cfEnv?.DATABASE_URL) {
    return jsonOk(EMPTY_CART);
  }

  const { db } = getDb(cfEnv!);
  const store = createStorefrontCartStore(db);
  const cart = await store.load(session.userId);

  return jsonOk(serializeCart(cart));
};
