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

export const fetchListings = createAsyncThunk(
  "listings/fetchAll",
  async (params: Record<string, string> | undefined, { rejectWithValue }) => {
    try {
      const { default: apiClient } = await import("@/services/api.client");
      const response = await apiClient.get<ListingsResponse>("/listings", { params });
      return response.data;
    } catch (error: unknown) {
      return rejectWithValue("Failed to fetch listings");
    }
  },
);

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

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

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

export const { resetListings } = listingsSlice.actions;
export default listingsSlice.reducer;
