import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { Listing, ListingsResponse } from "@/types/api/listing.types";

export const fetchByCategory = createAsyncThunk(
  "category/fetchBySlug",
  async (slug: string, { rejectWithValue }) => {
    try {
      const { default: apiClient } = await import("@/services/api.client");
      const response = await apiClient.get<ListingsResponse>(`/category/${slug}`);
      return response.data;
    } catch (error: unknown) {
      return rejectWithValue("Failed to fetch category listings");
    }
  },
);

interface CategoryState {
  items: Listing[];
  currentSlug: string | null;
  isLoading: boolean;
  error: string | null;
  currentPage: number;
  totalPages: number;
}

const initialState: CategoryState = {
  items: [],
  currentSlug: null,
  isLoading: false,
  error: null,
  currentPage: 1,
  totalPages: 1,
};

export const categorySlice = createSlice({
  name: "category",
  initialState,
  reducers: {
    resetCategory: (state) => {
      state.items = [];
      state.currentSlug = null;
      state.currentPage = 1;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchByCategory.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchByCategory.fulfilled, (state, action) => {
        state.isLoading = false;
        state.items = action.payload.data;
        state.totalPages = action.payload.last_page;
      })
      .addCase(fetchByCategory.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export const { resetCategory } = categorySlice.actions;
export default categorySlice.reducer;
