import { create } from "zustand";
import type { Lobby, LobbyMember } from "@/server/db/schema";

type LobbyStore = {
  lobby: Lobby;
  updateLobby: (lobby: Lobby) => void;
  resetLobby: (lobby?: Lobby) => void;
  members: Array<LobbyMember>;
  setMembers: (members: Array<LobbyMember>) => void;
  findMember: (playerId: string) => LobbyMember | null | undefined;
  addMember: (member: LobbyMember) => void;
  removeMember: (playerId: string, kicked?: boolean) => void;
  selectedGame: number;
  setSelectedGame: (gameId: number) => void;
};

export const useLobbyStore = create<LobbyStore>((set, get) => ({
  lobby: {} as Lobby,
  members: [],
  selectedGame: 0,
  setSelectedGame: (gameId) => set({ selectedGame: gameId }),
  updateLobby: (lobby) =>
    set((state) => ({ ...state, ...lobby, members: state.members })),
  setMembers: (members) => set({ members }),
  resetLobby: (lobby) => set({ lobby: lobby ?? ({} as Lobby) }),
  findMember: (playerId) => get().members.find((m) => m.playerId === playerId),
  addMember: (member) =>
    set((state) => {
      if (state.members.find((m) => m.playerId === member.playerId))
        return state;
      return { members: [...state.members, member] };
    }),
  removeMember: (playerId) =>
    set((state) => ({
      members: state.members.filter((m) => m.playerId !== playerId),
    })),
}));
