"use client";

import { createStore } from "zustand";
import { persist } from "zustand/middleware";

import { IChat, IChatMessage } from "@/entities/chats/types";

interface ChatState {
  currentChat: IChat | null;
  isAutoTopUp: boolean;
  suggestions: IChatMessage["suggestions"];
  _hasHydrated: boolean;
}

export type ChatActions = {
  setCurrentChat: (chat: IChat) => void;
  setIsAutoTopUp: (isAutoTopUp: boolean) => void;
  setSuggestions: (suggestions: IChatMessage["suggestions"]) => void;
  clearChatData: () => void;
  setHasHydrated: (hasHydrated: boolean) => void;
};

export type ChatStore = ChatState & ChatActions;

const initialState: ChatState = {
  currentChat: null,
  isAutoTopUp: false,
  suggestions: [],
  _hasHydrated: false,
};

export const createChatStore = (initState: ChatState = initialState) => {
  return createStore<ChatStore>()(
    persist(
      set => ({
        ...initState,
        setCurrentChat: (chat: IChat) => set({ currentChat: chat }),
        setIsAutoTopUp: (isAutoTopUp: boolean) => set({ isAutoTopUp }),
        setSuggestions: (suggestions: IChatMessage["suggestions"]) =>
          set({ suggestions }),
        clearChatData: () => set(initialState),

        setHasHydrated: (hasHydrated: boolean) =>
          set({ _hasHydrated: hasHydrated }),
      }),
      {
        name: "chat-storage",
        onRehydrateStorage: () => state => {
          if (state) {
            state.setHasHydrated(true);
          }
        },
      }
    )
  );
};
