import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";

export interface ClassifiedCategory {
  id: number;
  name: string;
  image: string;
  sort_order: number;
  status: number;
}

interface MarketplaceCategoryState {
  categories: ClassifiedCategory[];
  isLoading: boolean;
  error: string | null;
}

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

export const fetchMarketplaceCategories = createAsyncThunk(
  "marketplaceCategory/fetch",
  async (_, { rejectWithValue }) => {
    try {
      const res = await apiClient.post(API_ENDPOINTS.CLASSIFIED.GET_CATEGORIES);
      return res.data.result as ClassifiedCategory[];
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Failed to load marketplace categories";
      return rejectWithValue(message);
    }
  },
  {
    condition: (_, { getState }) => {
      const state = getState() as { marketplaceCategory: MarketplaceCategoryState };
      return (
        state.marketplaceCategory.categories.length === 0 &&
        !state.marketplaceCategory.isLoading
      );
    },
  }
);

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

export default marketplaceCategorySlice.reducer;
