import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { categoryService } from "@/services/categoryService";
import { Category } from "@/types/home";

interface CategoryState {
  categories: Category[];
  isLoading: boolean;
  error: string | null;
}

const initialState: CategoryState = {
  categories: [],
  isLoading: false,
  error: null,
};

export const fetchCategories = createAsyncThunk(
  "category/fetch",
  async (_, { rejectWithValue }) => {
    try {
      const res = await categoryService.getCategories();
      if (res.status !== 200) return rejectWithValue(res.message);
      return res.result.map(categoryService.mapCategory);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Failed to load categories";
      return rejectWithValue(message);
    }
  },
  {
    // Skip fetch if categories are already loaded
    condition: (_, { getState }) => {
      const state = getState() as { category: CategoryState };
      return state.category.categories.length === 0 && !state.category.isLoading;
    },
  },
);

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

export default categorySlice.reducer;
