import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { moreProductsService, MoreProduct } from "@/services/moreProductsService";

interface MoreProductsState {
  items: MoreProduct[];
  isLoading: boolean;
  error: string | null;
}

const initialState: MoreProductsState = {
  items: [],
  isLoading: false,
  error: null,
};

export const fetchMoreProducts = createAsyncThunk(
  "moreProducts/fetch",
  async (_, { rejectWithValue }) => {
    try {
      const res = await moreProductsService.getProducts();
      if (res.status !== 200) return rejectWithValue(res.message);
      return res.result.filter((p) => p.status === 1);
    } catch (err) {
      return rejectWithValue("Failed to load products");
    }
  },
);

const moreProductsSlice = createSlice({
  name: "moreProducts",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchMoreProducts.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchMoreProducts.fulfilled, (state, action) => {
        state.isLoading = false;
        state.items = action.payload;
      })
      .addCase(fetchMoreProducts.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export default moreProductsSlice.reducer;
