import { useGetRulesQuery } from "@/redux/api/rulesApi";

type CompanyRuleAction =
  | "edit"
  | "delete"
  | "view"
  | "viewall"
  | "create"
  | string;

type UseCompanyRuleParams = {
  companyId?: string;
  key: string;
  action?: CompanyRuleAction;
  role?: string;
  skip?: boolean;
};

const normalizeRole = (role?: string) =>
  String(role || "")
    .toLowerCase()
    .replace(/[\s_-]/g, "");

export const getCompanyRuleAccess = ({
  isEnabled,
  role,
}: {
  isEnabled: boolean;
  role?: string;
}) => {
  const normalizedRole = normalizeRole(role);
  if (normalizedRole === "superadmin") return true;
  return isEnabled;
};

export const useCompanyRule = ({
  companyId,
  key,
  action,
  role,
  skip = false,
}: UseCompanyRuleParams) => {
  const resolvedCompanyId = companyId || "";

  const { data, isLoading, isFetching, ...rest } = useGetRulesQuery(
    { companyId: resolvedCompanyId, key },
    { skip: skip || !resolvedCompanyId },
  );

  const isEnabled =
    data?.data?.rules?.[key] === true || data?.data?.[key] === true;
  const isAllowed = getCompanyRuleAccess({
    isEnabled,
    role,
  });

  return {
    isEnabled,
    isAllowed,
    action,
    isLoading: isLoading || isFetching,
    data,
    ...rest,
  };
};
