import { create } from 'zustand';
import type { UserStatus } from './auth.ts';

export interface PresenceEntry {
  userId: string;
  username: string;
  status: UserStatus;
}

interface PresenceState {
  presences: Record<string, PresenceEntry>;
  /** Upsert a single user's presence from a WS event. */
  updatePresence: (userId: string, username: string, status: UserStatus) => void;
  /** Get a user's current presence; defaults to offline. */
  getPresence: (userId: string) => PresenceEntry;
}

const DEFAULT_PRESENCE: PresenceEntry = {
  userId: '',
  username: '',
  status: 'offline',
};

export const usePresenceStore = create<PresenceState>((set, get) => ({
  presences: {},

  updatePresence: (userId, username, status) =>
    set((state) => ({
      presences: {
        ...state.presences,
        [userId]: { userId, username, status },
      },
    })),

  getPresence: (userId) => get().presences[userId] ?? DEFAULT_PRESENCE,
}));
