import { createTypedReducerWithImmer } from "@insite/client-framework/Common/CreateTypedReducer";
import { GetCartPromotionsApiParameter } from "@insite/client-framework/Services/CartService";
import { getDataViewKey } from "@insite/client-framework/Store/Data/DataState";
import { PromotionsState } from "@insite/client-framework/Store/Data/Promotions/PromotionsState";
import { PromotionCollectionModel } from "@insite/client-framework/Types/ApiModels";
import { Draft } from "immer";

const initialState: PromotionsState = {
    isLoading: {},
    dataViews: {},
    errorStatusCodeById: {},
};

const reducer = {
    "Data/Promotions/BeginLoadPromotions": (
        draft: Draft<PromotionsState>,
        action: { parameter: GetCartPromotionsApiParameter },
    ) => {
        draft.dataViews[getDataViewKey(action.parameter)] = {
            isLoading: true,
            fetchedDate: new Date(),
        };
    },

    "Data/Promotions/CompleteLoadPromotions": (
        draft: Draft<PromotionsState>,
        action: { parameter: GetCartPromotionsApiParameter; collection: PromotionCollectionModel },
    ) => {
        const dataView = {
            isLoading: false,
            value: action.collection.promotions!,
            fetchedDate: new Date(),
        };

        draft.dataViews[getDataViewKey(action.parameter)] = dataView;
    },

    "Data/Promotions/FailedToLoadPromotions": (
        draft: Draft<PromotionsState>,
        action: { cartId: string; status: number },
    ) => {
        delete draft.isLoading[action.cartId];
        if (draft.errorStatusCodeById) {
            draft.errorStatusCodeById[action.cartId] = action.status;
        }
    },

    "Data/Promotions/Reset": () => {
        return initialState;
    },
};

export default createTypedReducerWithImmer(initialState, reducer);
