/**
 * Checkout Store
 *
 * Zustand store for checkout flow with localStorage persistence.
 * Stores cart data and checkout session for authenticated users.
 */

import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import type { CartItem } from "@customer-portal/domain/checkout";

interface CheckoutState {
  // Cart data
  cartItem: CartItem | null;
  cartParamsSignature: string | null;
  checkoutSessionId: string | null;
  checkoutSessionExpiresAt: string | null;

  // Cart timestamp for staleness detection
  cartUpdatedAt: number | null;
}

interface CheckoutActions {
  // Cart actions
  setCartItem: (item: CartItem) => void;
  setCartItemFromParams: (item: CartItem, signature: string) => void;
  setCheckoutSession: (session: { id: string; expiresAt: string }) => void;

  // Reset
  clear: () => void;

  // Cart recovery
  isCartStale: (maxAgeMs?: number) => boolean;
}

type CheckoutStore = CheckoutState & CheckoutActions;

const initialState: CheckoutState = {
  cartItem: null,
  cartParamsSignature: null,
  checkoutSessionId: null,
  checkoutSessionExpiresAt: null,
  cartUpdatedAt: null,
};

export const useCheckoutStore = create<CheckoutStore>()(
  persist(
    (set, get) => ({
      ...initialState,

      // Cart actions
      setCartItem: (item: CartItem) =>
        set({
          cartItem: item,
          cartUpdatedAt: Date.now(),
        }),

      setCartItemFromParams: (item: CartItem, signature: string) => {
        const { cartParamsSignature, cartItem } = get();
        const signatureChanged = cartParamsSignature !== signature;
        const hasExistingCart = cartItem !== null || cartParamsSignature !== null;

        if (signatureChanged && hasExistingCart) {
          set(initialState);
        }

        if (!signatureChanged && cartItem) {
          // Allow refreshing cart totals without resetting progress
          set({
            cartItem: item,
            cartUpdatedAt: Date.now(),
          });
          return;
        }

        set({
          cartItem: item,
          cartParamsSignature: signature,
          cartUpdatedAt: Date.now(),
        });
      },

      setCheckoutSession: session =>
        set({
          checkoutSessionId: session.id,
          checkoutSessionExpiresAt: session.expiresAt,
        }),

      // Reset
      clear: () => set(initialState),

      // Cart recovery - check if cart is stale (default 24 hours)
      isCartStale: (maxAgeMs = 24 * 60 * 60 * 1000) => {
        const { cartUpdatedAt, checkoutSessionExpiresAt } = get();
        if (checkoutSessionExpiresAt) {
          const expiresAt = new Date(checkoutSessionExpiresAt).getTime();
          if (!Number.isNaN(expiresAt) && Date.now() >= expiresAt) {
            return true;
          }
        }
        if (!cartUpdatedAt) return false;
        return Date.now() - cartUpdatedAt > maxAgeMs;
      },
    }),
    {
      name: "checkout-store",
      version: 1,
      storage: createJSONStorage(() => localStorage),
      migrate: (persistedState, version) => {
        // Version 0 (or undefined) -> Version 1: no structural changes, just initialize missing fields
        if (version === 0 || version === undefined) {
          const state = persistedState as Partial<CheckoutState>;
          return {
            ...initialState,
            ...state,
          };
        }
        return persistedState as CheckoutState;
      },
      partialize: state => ({
        // Persist only essential data
        cartItem: state.cartItem
          ? {
              ...state.cartItem,
              // Avoid persisting potentially sensitive configuration details.
              configuration: {},
            }
          : null,
        cartParamsSignature: state.cartParamsSignature,
        checkoutSessionId: state.checkoutSessionId,
        checkoutSessionExpiresAt: state.checkoutSessionExpiresAt,
        cartUpdatedAt: state.cartUpdatedAt,
      }),
    }
  )
);
