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 mainGetGuildsForUpdateOrCreateService = createAsyncThunk(
  "MAIN_GET_GUILDS_FOR_UPDATE_OR_CREATE_SERVICE",
  async (payload, { dispatch }) => {
    dispatch(LOADING_START());
    try {
      const { data, status } = await axios.get(
        "main_get_guilds_for_update_or_create/",
        {
          params: {
            national_code: payload.national_code,
            update: payload.update || false,
            role: getRoleFromUrl(),
          },
        }
      );
      dispatch(LOADING_END());
      return { data, status };
    } catch (e) {
      dispatch(LOADING_END());

      if (e.response?.status === 403) {
        const errorMessage =
          e.response?.data?.result ||
          e.response?.data?.message ||
          "دسترسی غیرمجاز";
        return { error: errorMessage, status: 403 };
      }

      const errorMessage =
        e.response?.data?.result ||
        e.response?.data?.message ||
        "خطا در دریافت اطلاعات";
      return { error: errorMessage };
    }
  }
);
