import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { RootState } from "@/store/store";
import type { NavCategory, NavCategoryResponse } from "@/types/api/navCategory.types";

export const fetchNavCategories = createAsyncThunk(
  "navCategories/fetch",
  async (_, { getState, rejectWithValue }) => {
    // Guard: never fetch more than once
    const state = getState() as RootState;
    if (state.navCategories.isLoaded) return state.navCategories.items;

    try {
      const { default: apiClient } = await import("@/services/api.client");
      const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
      const { data } = await apiClient.post<NavCategoryResponse>(
        API_ENDPOINTS.GET_CATEGORY,
        {},
      );
      return (data.result ?? []).filter((c) => c.status === 1);
    } catch (err) {
      const msg = (err as Error)?.message ?? "Failed to load categories.";
      return rejectWithValue(msg);
    }
  },
);

interface NavCategoryState {
  items: NavCategory[];
  isLoaded: boolean;
  isLoading: boolean;
  error: string | null;
}

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

const navCategorySlice = createSlice({
  name: "navCategories",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchNavCategories.pending, (state) => {
        if (!state.isLoaded) state.isLoading = true;
      })
      .addCase(fetchNavCategories.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isLoaded = true;
        state.items = action.payload as NavCategory[];
      })
      .addCase(fetchNavCategories.rejected, (state, action) => {
        state.isLoading = false;
        state.error = (action.payload as string) ?? "Something went wrong.";
      });
  },
});

export default navCategorySlice.reducer;
