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

export const fetchSlaughterBroadcastAndProducts = createAsyncThunk(
  "SLAUGHTER_FETCH_BROADCAST_AND_PRODUCTS",
  async (d, { dispatch }) => {
    dispatch(LOADING_START());
    try {
      const endpointPart =
        getRoleFromUrl() === "KillHouse" ? "kill-house" : "steward";
      const role = getRoleFromUrl();

      const [broadcastResponse, productsResponse] = await Promise.all([
        axios.get(`${endpointPart}-sales-info-dashboard/`, {
          params: {
            role: role,
            ...d,
          },
        }),
        axios.get("roles-products", {
          params: {
            role: role,
            role_key: d.role_key || "",
          },
        }),
      ]);

      return {
        broadcastData: broadcastResponse.data,
        productsData: productsResponse.data,
      };
    } catch (error) {
      console.error("Data fetching failed:", error);
      throw error;
    } finally {
      dispatch(LOADING_END());
    }
  }
);

export const fetchRolesProducts = createAsyncThunk(
  "SLAUGHTER_FETCH_ROLES_PRODUCTS",
  async (d, { dispatch }) => {
    try {
      dispatch(LOADING_START());
      const productsResponse = await axios.get("roles-products", {
        params: {
          role: getRoleFromUrl(),
          role_key: d.role_key || "",
        },
      });
      dispatch(LOADING_END());

      return {
        productsData: productsResponse.data,
      };
    } catch (error) {
      dispatch(LOADING_END());
      throw error;
    }
  }
);
