import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { getRegion } from './service';
import type { RegionData } from './interface';
// Define types for group data and params
// Define types for group data and params

// Define an initial state
const initialState = {
  region: [] as RegionData[],
  status: 'loading',
  error: '',
  meta: { current_page: '', per_page: '', total: 0 }, // Add pagination property
};

// Simulate fetching group data from your service
// slice.ts
export const fetchRegion = createAsyncThunk('region/fetchRegion', async(searchQuery: any) => {
  const response = await getRegion(searchQuery); // Assuming getGroups returns an AxiosResponse
  return response.data;
});

const regionSlice = createSlice({
  name: 'region',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchRegion.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchRegion.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.region = action.payload.data;
        state.meta = action.payload.meta;
      })
      .addCase(fetchRegion.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message ?? 'An error occurred'; // Handle undefined gracefully
      });
  },
});

export default regionSlice.reducer;
