import { create } from 'zustand';
import { api } from '../api/client';
import type { Session, ExerciseStats } from '../types';
import { useToastStore } from './toastStore';

interface HistoryState {
  sessions: Session[];
  loading: boolean;
  stats: ExerciseStats[];
  fetchSessions: (limit?: number, offset?: number) => Promise<void>;
  fetchSession: (id: number) => Promise<Session | null>;
  fetchStats: () => Promise<void>;
}

export const useHistoryStore = create<HistoryState>((set) => ({
  sessions: [],
  loading: false,
  stats: [],

  fetchSessions: async (limit, offset) => {
    set({ loading: true });
    try {
      const sessions = await api.sessions.list(limit, offset);
      set({ sessions: sessions || [], loading: false });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Laden';
      useToastStore.getState().addToast('error', message);
      set({ loading: false });
    }
  },

  fetchSession: async (id) => {
    try {
      return await api.sessions.get(id);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Session nicht gefunden';
      useToastStore.getState().addToast('error', message);
      return null;
    }
  },

  fetchStats: async () => {
    try {
      const stats = await api.stats.overview();
      set({ stats: stats || [] });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Laden';
      useToastStore.getState().addToast('error', message);
    }
  },
}));
