import {
  getCartSessionFromRequestCookies,
  getRawStorefrontCart,
  normalizeStorefrontCart,
} from "@/lib/storefront-cart";
import { getStorefrontCheckoutState } from "@/lib/storefront-checkout";
import { getWishlistFromCookies } from "@/lib/storefront-wishlist";
import type {
  StorefrontCart,
  StorefrontCheckoutState,
  StorefrontCheckoutStep,
  StorefrontWishlist,
} from "@/types/storefront";

const EMPTY_CART: StorefrontCart = {
  items: [],
  itemCount: 0,
  subtotal: "0,00 €",
  total: "0,00 €",
  isEmpty: true,
};

const EMPTY_WISHLIST: StorefrontWishlist = {
  items: [],
  itemCount: 0,
  isEmpty: true,
};

export async function getCart(): Promise<StorefrontCart> {
  try {
    const session = await getCartSessionFromRequestCookies();
    const result = await getRawStorefrontCart(session);

    return normalizeStorefrontCart(result.payload);
  } catch {
    return EMPTY_CART;
  }
}

export async function getWishlist(): Promise<StorefrontWishlist> {
  try {
    return await getWishlistFromCookies();
  } catch {
    return EMPTY_WISHLIST;
  }
}

export async function getCheckoutState(): Promise<StorefrontCheckoutState | null> {
  try {
    const session = await getCartSessionFromRequestCookies();
    const result = await getStorefrontCheckoutState(session);

    return result.checkout;
  } catch {
    return null;
  }
}

export async function getCheckoutSteps(input?: {
  isLoggedIn?: boolean;
}): Promise<StorefrontCheckoutStep[]> {
  const isLoggedIn = Boolean(input?.isLoggedIn);

  return [
    {
      id: "login",
      label: "Prijava",
      description: isLoggedIn
        ? "Kupac je prijavljen i može nastaviti na dostavu."
        : "Prijava ili nastavak kao gost.",
      isActive: true,
    },
    {
      id: "shipping",
      label: "Dostava",
      description: "Podaci za naplatu i dostavu.",
      isActive: false,
    },
    {
      id: "payment",
      label: "Način plaćanja",
      description: "Odabir metode plaćanja i potvrda narudžbe.",
      isActive: false,
    },
  ];
}
