/**
 * Billing Store (Zustand)
 * Manages credit balance and usage tracking
 */
import { create } from 'zustand';
import {
  fetchCreditBalance,
  fetchUsageSummary,
  CreditBalance,
  UsageSummary,
} from '../services/api';

interface BillingState {
  balance: CreditBalance | null;
  usageSummary: UsageSummary | null;
  loading: boolean;
  error: string | null;
  
  // Actions
  loadBalance: () => Promise<void>;
  loadUsageSummary: (startDate?: string, endDate?: string) => Promise<void>;
  reset: () => void;
}

export const useBillingStore = create<BillingState>((set, get) => ({
  balance: null,
  usageSummary: null,
  loading: false,
  error: null,
  
  loadBalance: async () => {
    set({ loading: true, error: null });
    try {
      const balance = await fetchCreditBalance();
      set({ balance, loading: false });
    } catch (error: any) {
      set({ error: error.message, loading: false });
    }
  },
  
  loadUsageSummary: async (startDate?: string, endDate?: string) => {
    set({ loading: true, error: null });
    try {
      const summary = await fetchUsageSummary(startDate, endDate);
      set({ usageSummary: summary, loading: false });
    } catch (error: any) {
      set({ error: error.message, loading: false });
    }
  },
  
  reset: () => {
    set({
      balance: null,
      usageSummary: null,
      loading: false,
      error: null,
    });
  },
}));

