import { create } from "zustand";
import { Message, PrivateChannel } from "../types/discord";

interface ChatStore {
  privateChannels: Record<string, PrivateChannel>;
  messages: Record<string, Message[]>;
  setPrivateChannels: (value: PrivateChannel[]) => void;
  addMessage: (channelId: string, message: Message) => void;
  appendOlder: (channelId: string, olderMessages: Message[]) => void;
  clearChannel: (channelId: string) => void;
  noMoreOlder: Record<string, boolean>;
  setNoMoreOlder: (channelId: string, value: boolean) => void;
}

export const useChatStore = create<ChatStore>((set) => ({
  privateChannels: {},
  messages: {},
  setPrivateChannels: (channels) => {
    const record: Record<string, PrivateChannel> = {};
    channels.forEach((ch) => {
      if (ch.id) record[ch.id] = ch;
    });
    set({ privateChannels: record });
  },
  addMessage: (channelId, message) =>
    set((state) => {
      const existing = state.messages[channelId] ?? [];
      if (message?.id && existing.some((m) => m.id === message.id))
        return state;
      return {
        messages: {
          ...state.messages,
          [channelId]: [message, ...existing],
        },
      };
    }),
  appendOlder: (channelId, olderMessages) =>
    set((state) => {
      const existing = state.messages[channelId] ?? [];
      if (!Array.isArray(olderMessages) || olderMessages.length === 0) {
        return state;
      }
      const existingIds = new Set(existing.map((m) => m.id));
      const filteredOlder = olderMessages.filter((m) => m?.id && !existingIds.has(m.id));
      if (filteredOlder.length === 0) return state;
      return {
        messages: {
          ...state.messages,
          [channelId]: [...existing, ...filteredOlder],
        },
      };
    }),
  clearChannel: (channelId) =>
    set((state) => {
      const copy = { ...state.messages };
      delete copy[channelId];
      return { messages: copy };
    }),
  noMoreOlder: {},
  setNoMoreOlder: (channelId, value) =>
    set((state) => ({
      noMoreOlder: { ...state.noMoreOlder, [channelId]: value },
    })),
}));