import { create } from "zustand";
import { api } from "../lib/api.ts";

export interface Member {
  id: string;
  username: string;
  display_name: string;
  avatar: string;
  status: "online" | "idle" | "dnd" | "offline";
  status_text: string;
}

interface MemberState {
  membersByServer: Record<string, Member[]>;
  isLoading: boolean;
  fetchMembers: (serverId: string) => Promise<void>;
  updateMemberStatus: (userId: string, status: Member["status"]) => void;
}

export const useMemberStore = create<MemberState>((set) => ({
  membersByServer: {},
  isLoading: false,

  fetchMembers: async (serverId) => {
    set({ isLoading: true });
    try {
      const members = await api.get<Member[]>(
        `/servers/${serverId}/members`,
      );
      set((state) => ({
        membersByServer: { ...state.membersByServer, [serverId]: members },
        isLoading: false,
      }));
    } catch {
      set({ isLoading: false });
    }
  },

  updateMemberStatus: (userId, status) =>
    set((state) => {
      const next: Record<string, Member[]> = {};
      for (const [serverId, list] of Object.entries(state.membersByServer)) {
        next[serverId] = list.map((m) =>
          m.id === userId ? { ...m, status } : m,
        );
      }
      return { membersByServer: next };
    }),
}));
