import { create } from 'zustand';
import { api } from '../lib/api';

type NotificationLevel = 'all' | 'mentions' | 'none';

interface NotificationSettingsState {
  settings: Record<string, NotificationLevel>;
  initialized: boolean;
  loaded: boolean;
  fetchSettings: () => Promise<void>;
  setLevel: (channelId: string, level: NotificationLevel) => Promise<void>;
}

export const useNotificationSettingsStore = create<NotificationSettingsState>()((set) => ({
  settings: {},
  initialized: false,
  loaded: false,

  fetchSettings: async () => {
    try {
      const settings = await api.get<Record<string, NotificationLevel>>('/channels/me/notifications');
      set({ settings, loaded: true, initialized: true });
    } catch {
      set({ loaded: true, initialized: true });
    }
  },

  setLevel: async (channelId: string, level: NotificationLevel) => {
    await api.put(`/channels/${channelId}/notifications`, { level });
    set((state) => ({
      settings: { ...state.settings, [channelId]: level },
    }));
  },
}));
