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

const useReportStore = create((set) => ({
  dailySales: [],
  monthlySales: [],
  productStock: [],
  customerPurchases: [],
  loading: false,
  error: null,

  fetchDailySales: async (date) => {
    set({ loading: true, error: null });
    try {
      const response = await api.get('/reports/daily-sales', { params: { date } });
      set({ dailySales: response.data?.data || [], loading: false });
      return response.data;
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to fetch daily sales' });
      return null;
    }
  },

  fetchMonthlySales: async (startDate, endDate) => {
    set({ loading: true, error: null });
    try {
      const response = await api.get('/reports/monthly-sales', {
        params: { start_date: startDate, end_date: endDate },
      });
      set({ monthlySales: response.data?.data || [], loading: false });
      return response.data;
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to fetch monthly sales' });
      return null;
    }
  },

  fetchProductStock: async () => {
    set({ loading: true, error: null });
    try {
      const response = await api.get('/reports/product-stock');
      // backend returns { success: true, data: [...] }
      set({ productStock: response.data?.data || [], loading: false });
      return response.data;
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to fetch product stock' });
      return null;
    }
  },

  fetchCustomerPurchases: async (customerName) => {
    set({ loading: true, error: null });
    try {
      const response = await api.get(`/reports/customer-purchase/${customerName}`);
      set({ customerPurchases: response.data?.data || [], loading: false });
      return response.data;
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to fetch customer purchases' });
      return null;
    }
  },

  clearError: () => set({ error: null }),
}));

export default useReportStore;
