import { IAssistant } from "@/api/resources/ChatsCategories";
import { createSlice, createSelector } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";

interface IChat {
    assistant: IAssistant | null;
    chatId: string;
    isAutoRefill: boolean;
    isPayedFirstPurchase: boolean;
    dateEndChatting: string;
}

const initialState: IChat = {
    assistant: null,
    chatId: "",
    isAutoRefill: true,
    isPayedFirstPurchase: false,
    dateEndChatting: ""
};

const chatSlice = createSlice({
    name: "chat",
    initialState,
    reducers: {
        update(state, action: PayloadAction<Partial<IChat>>) {
            return { ...state, ...action.payload };
        },
        updateAssistant(state, action: PayloadAction<IAssistant>) {
            return { ...state, assistant: action.payload };
        },
        updateChatId(state, action: PayloadAction<string>) {
            return { ...state, chatId: action.payload };
        },
        updateIsAutoRefill(state, action: PayloadAction<boolean>) {
            return { ...state, isAutoRefill: action.payload };
        },
        updateIsPayedFirstPurchase(state, action: PayloadAction<boolean>) {
            return { ...state, isPayedFirstPurchase: action.payload };
        },
        updateDateEndChatting(state, action: PayloadAction<string>) {
            return { ...state, dateEndChatting: action.payload };
        },
    },
    extraReducers: (builder) => builder.addCase("reset", () => initialState),
});

export const { actions } = chatSlice;

export const selectCurrentAssistant = createSelector(
    (state: { chat: IChat }) => state.chat.assistant,
    (chat) => chat
);

export const selectCurrentChatId = createSelector(
    (state: { chat: IChat }) => state.chat.chatId,
    (chat) => chat
);

export const selectIsAutoRefill = createSelector(
    (state: { chat: IChat }) => state.chat.isAutoRefill,
    (chat) => chat
);

export const selectIsPayedFirstPurchase = createSelector(
    (state: { chat: IChat }) => state.chat.isPayedFirstPurchase,
    (chat) => chat
);

export const selectDateEndChatting = createSelector(
    (state: { chat: IChat }) => state.chat.dateEndChatting,
    (chat) => chat
);

export default chatSlice.reducer;
