import { create } from "zustand"; import { ChatMessage } from "@repo/db"; import { socket } from "(dispatch)/socket"; interface ChatStore { ownId: null | string; selectedChat: string | null; chatOpen: boolean; setChatOpen: (open: boolean) => void; setSelectedChat: (chatId: string | null) => void; setOwnId: (id: string) => void; chats: Record< string, { name: string; notification: boolean; messages: ChatMessage[] } >; setChatNotification: (userId: string, notification: boolean) => void; sendMessage: (userId: string, message: string) => Promise; addChat: (userId: string, name: string) => void; addMessage: (userId: string, message: ChatMessage) => void; } export const useChatStore = create((set, get) => ({ ownId: null, chatOpen: false, selectedChat: null, setChatOpen: (open: boolean) => set({ chatOpen: open }), setSelectedChat: (chatId: string | null) => set({ selectedChat: chatId }), setOwnId: (id: string) => set({ ownId: id }), chats: {}, sendMessage: (userId: string, message: string) => { return new Promise((resolve, reject) => { socket.emit( "send-message", { userId, message }, ({ error }: { error?: string }) => { if (error) { reject(error); } else { resolve(); } }, ); }); }, addChat: (userId, name) => { set((state) => ({ chats: { ...state.chats, // Bestehende Chats beibehalten [userId]: { name, notification: false, messages: [] }, // Neuen Chat hinzufügen }, })); }, setChatNotification: (userId, notification) => { const chat = get().chats[userId]; if (!chat) return; console.log("setChatNotification", userId, notification); set((state) => { return { chats: { ...state.chats, [userId]: { ...chat, notification, }, }, }; }); }, addMessage: (userId: string, message: ChatMessage) => { set((state) => { const user = state.chats[userId] || { name: userId, messages: [], notification: false, }; const isSender = message.senderId === state.ownId; return { selectedChat: state.selectedChat ? state.selectedChat : userId, chats: { ...state.chats, [userId]: { ...user, name: isSender ? message.receiverName : message.senderName, notification: !isSender && (state.selectedChat !== userId || !state.chatOpen), messages: [...user.messages, message], // Neuen Zustand erzeugen }, }, }; }); }, })); socket.on( "chat-message", ({ userId, message }: { userId: string; message: ChatMessage }) => { const store = useChatStore.getState(); console.log("chat-message", userId, message); // Update the chat store with the new message store.addMessage(userId, message); }, );