import { create } from 'zustand';
import * as habitService from '../services/habitService';

const useHabitStore = create((set, get) => ({
  habits: [],
  habitLogs: {},
  loading: false,
  error: null,

  setHabits: (habits) => set({ habits }),

  fetchHabits: async (identityId) => {
    set({ loading: true, error: null });
    try {
      const habits = await habitService.getHabits(identityId);
      set({ habits, loading: false });
    } catch (e) {
      set({ loading: false, error: e.message });
    }
  },

  loadTodayLogs: async () => {
    const { habits } = get();
    if (!habits.length) return {};

    try {
      const logs = await habitService.getTodayHabitLogs(habits.map((h) => h.id));
      set({ habitLogs: logs });
      return logs;
    } catch (e) {
      set({ error: e.message });
      return {};
    }
  },

  toggleHabit: async (habitId) => {
    const { habitLogs } = get();
    const newValue = !habitLogs[habitId];

    // Optimistic update
    set({ habitLogs: { ...habitLogs, [habitId]: newValue } });

    try {
      await habitService.saveHabitLog(habitId, newValue);
    } catch (e) {
      // Rollback
      set({ habitLogs: { ...get().habitLogs, [habitId]: !newValue }, error: e.message });
    }
  },

  // Reset on logout
  reset: () => set({ habits: [], habitLogs: {}, loading: false, error: null }),
}));

export default useHabitStore;
