import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { salesApi } from '@/services/api';

export interface SalesState {
  data: any;
  loading: boolean;
  error: string | null;
}

const initialState: SalesState = {
  data: null,
  loading: false,
  error: null
};

export const fetchSalesData = createAsyncThunk(
  'sales/fetchData',
  async (agentId: string) => {
    try {
      const response = await salesApi.getSalesData(agentId);
      return response.data;
    } catch (error) {
      throw new Error('Failed to fetch sales data');
    }
  }
);

const salesSlice = createSlice({
  name: 'sales',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchSalesData.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchSalesData.fulfilled, (state, action) => {
        state.loading = false;
        state.data = action.payload;
      })
      .addCase(fetchSalesData.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'An error occurred';
      });
  },
});

export default salesSlice.reducer;
