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

export const provinceGetTotalKillhouseRemainWeight = createAsyncThunk(
  "PROVINCE_GET_TOTAL_KILLHOUSE_REMAIN_WEIGHT",
  async (params, { dispatch }) => {
    try {
      dispatch(LOADING_START());

      const pathname =
        typeof window !== "undefined" ? window.location.pathname : "";
      const isStewardPage =
        pathname?.split("/").filter(Boolean).pop() === "steward";

      const endpoint = isStewardPage
        ? "total-steward-remain-weight/"
        : "total-kill-house-remain-weight/";

      const requestParams = {
        search: params?.search ?? "filter",
        value: params?.value ?? "",
        page: params?.page ?? 1,
        page_size: params?.page_size ?? (isStewardPage ? 40 : 10),
        quota: params?.quota ?? false,
      };

      if (params?.date1) {
        requestParams.date1 = params.date1;
      }

      if (params?.date2) {
        requestParams.date2 = params.date2;
      }

      if (isStewardPage) {
        requestParams.owner_type = params?.owner_type ?? "steward";
      } else {
        requestParams.role = params?.role ?? "SuperAdmin";
      }

      const { data, status } = await axios.get(endpoint, {
        params: requestParams,
      });
      dispatch(LOADING_END());
      return { data, status };
    } catch (e) {
      dispatch(LOADING_END());
      return { error: e.response?.data?.result || "خطا در دریافت اطلاعات" };
    }
  }
);

export const provinceGetTotalKillhouseArchiveDashboard = createAsyncThunk(
  "PROVINCE_GET_TOTAL_KILLHOUSE_ARCHIVE_DASHBOARD",
  async (params, { dispatch }) => {
    try {
      dispatch(LOADING_START());
      const isSteward = params?.owner_type === "steward";
      const endpoint = isSteward
        ? "total-guild-steward-archive-dashboard/"
        : "total-kill-house-archive-dashboard/";

      const requestParams = {
        search: params?.search ?? "filter",
        value: params?.value ?? "",
        date1: params?.date1,
        date2: params?.date2,
        page: params?.page ?? 1,
        page_size: params?.page_size ?? 10,
      };

      if (isSteward) {
        requestParams.owner_type = params.owner_type ?? "steward";
      } else {
        requestParams.role = params?.role ?? "SuperAdmin";
      }

      const { data, status } = await axios.get(endpoint, {
        params: requestParams,
      });
      dispatch(LOADING_END());
      return { data, status };
    } catch (e) {
      dispatch(LOADING_END());
      return { error: e.response?.data?.result || "خطا در دریافت اطلاعات" };
    }
  }
);
