import moment from "moment";
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import type { Action, FromDomain } from "@root/model/autoPay";

interface CartStore {
    notEnoughMoneyAmount: number;
    siteReadyPayCart: Record<string, string> | null;
    fromDomain: FromDomain | null;
    backWay: string;
    action: Action | null;
    additionalinformation: string;
}
const initialState: CartStore = {
    notEnoughMoneyAmount: 0,
    siteReadyPayCart: null,
    fromDomain: null,
    backWay: "",
    action: null,
    additionalinformation: ""
}

//Была попытка оплатить корзину. Тут записанна недостающая сумма.
export const allTypesOfPurchases = create<CartStore>()(
    devtools(
      persist(
        () => initialState,
        {
          name: 'siteReadyPayCart', // Ключ для localStorage
          partialize: (state) => ({ 
            // Сохраняем ТОЛЬКО siteReadyPayCart
            siteReadyPayCart: state.siteReadyPayCart 
          }),
        }
      ),
      {
        name: "cartStore",
        enabled: process.env.NODE_ENV === "development",
      }
    )
  );

export const setSiteReadyPayCart = (flag: Record<string, string> | null) => allTypesOfPurchases.setState({ siteReadyPayCart: flag });
export const setNotEnoughMoneyAmount = (amount: number) => allTypesOfPurchases.setState({ notEnoughMoneyAmount: amount });
export const setFromDomain = (fromDomain: FromDomain) => allTypesOfPurchases.setState({ fromDomain });
export const setBackWay = (backWay: string) => allTypesOfPurchases.setState({ backWay });
export const setAction = (action: Action) => allTypesOfPurchases.setState({ action });
export const setAdditionalinformation = (additionalinformation: string) => allTypesOfPurchases.setState({ additionalinformation });

export const startPayCartProcess = (userId: string) => setSiteReadyPayCart({ [userId]: moment().add(20, 'minutes').format("X") });
export const cancelPayCartProcess = () => {
    setSiteReadyPayCart(null);
    allTypesOfPurchases.setState({
        fromDomain: null,
        backWay: "",
        action: null        
    })
};


export const calcTimeOfReadyPayCart = (deadline: string) => {
    const ready = Number(deadline) > Number(moment().format("X"))
    if (!ready) {
        cancelPayCartProcess()
    }
    return ready
}
