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

interface ReadStatesState {
  states: Record<string, string>; // channel_id -> last_read_message_id
  loaded: boolean;
  fetchStates: () => Promise<void>;
  markRead: (channelId: string, messageId: string) => Promise<void>;
  hasUnread: (channelId: string) => boolean; // true if no read state (never viewed)
}

export const useReadStatesStore = create<ReadStatesState>()((set, get) => ({
  states: {},
  loaded: false,

  fetchStates: async () => {
    try {
      const states = await api.get<Record<string, string>>('/users/me/read-states');
      set({ states, loaded: true });
    } catch {
      set({ loaded: true });
    }
  },

  markRead: async (channelId: string, messageId: string) => {
    set((state) => ({
      states: { ...state.states, [channelId]: messageId },
    }));
    try {
      await api.put(`/channels/${channelId}/read`, { last_read_message_id: messageId });
    } catch {
      // optimistic update, ignore failure
    }
  },

  hasUnread: (channelId: string): boolean => {
    const state = get().states;
    // No read state means the user has never viewed this channel
    return !(channelId in state);
  },
}));
