import { createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";

export const provinceGetDirectBuyingPoultryRequests = createAsyncThunk(
  "PROVINCE_GET_DIRECT_BUYING_POULTRY_REQUESTS",
  async (params, { dispatch }) => {
    dispatch(LOADING_START());
    try {
      const {
        selectedBreeds = [],
        selectedCities = [],
        showRemaining = false,
        minPrice = "",
        maxPrice = "",
        minAge = "",
        maxAge = "",
        textValue = "",
        page = 1,
        perPage = 20,
      } = params || {};

      const cityParams =
        selectedCities.length > 0 ? `&city=${selectedCities.join(",")}` : "";
      const minPriceParam = minPrice ? `&min_amount=${minPrice}` : "";
      const maxPriceParam = maxPrice ? `&max_amount=${maxPrice}` : "";

      const { data, status } = await axios.get(
        `direct-buying-poultry-requests?breed=${selectedBreeds.join(
          ","
        )}${cityParams}&remain=${showRemaining}${minPriceParam}${maxPriceParam}&weight=&min_age=${minAge}&max_age=${maxAge}&role=${getRoleFromUrl()}&search=filter&value=${
          textValue || ""
        }&page=${page}&page_size=${perPage}`
      );
      dispatch(LOADING_END());
      return { data, status };
    } catch (e) {
      dispatch(LOADING_END());
      return { error: e.response?.data?.result || e.message };
    }
  }
);
