import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { getCustomer, getCustomerById } from './service';
import type { CustomerState } from './interface'; // Define your CustomerData type
// Define an initial state
const initialState: CustomerState = {
  customers: [],
  customerDetail:[],
  status: 'loading',
  error: '',
  // meta: { current_page: '', per_page: '', total: 0 } // Add pagination property
};

export const fetchCustomers = createAsyncThunk(
  'customer/fetchCustomer',
  async(searchQuery: any) => {
    const response = await getCustomer(searchQuery);
    return response;
  }
);
export const fetchCustomerById = createAsyncThunk(
  'customer/getCustomerById',
  async(searchQuery: any) => {
    const customer = await getCustomerById(searchQuery);
    return customer;
  }
);
// Create the customer slice
const customerSlice = createSlice({
  name: 'customer',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchCustomers.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchCustomers.fulfilled, (state, action) => {
        state.status = 'succeeded';

        state.customers = action?.payload?.data?.data;
      })
      .addCase(fetchCustomers.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message ?? 'An error occurred';
      })
      .addCase(fetchCustomerById.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchCustomerById.fulfilled, (state, action) => {
        state.status = 'succeeded';

        state.customerDetail = action?.payload?.data?.data;
      })
      .addCase(fetchCustomerById.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message ?? 'An error occurred';
      });
  },
});

export default customerSlice.reducer;
