import { useQuery } from 'react-query';

import { useRequiredAuth } from 'src/contexts/JWTContext';
import usePermissions from 'src/hooks/usePermissions';
import { orgChartKeys } from 'src/pages/dashboard/orgChart/queries';
import { getUserSubordinates } from 'src/services/orgChart';
import { UserPermissions } from 'src/utils/permissions';

const SUBORDINATES_NEEDED_PERMISSIONS = [
  UserPermissions.VIEW_ORGANIZATION_CHARTS,
  UserPermissions.VIEW_GOALS,
  UserPermissions.VIEW_VACATIONS,
  UserPermissions.VIEW_TIME_TRACKING,
  UserPermissions.VIEW_SHIFTS,
  UserPermissions.VIEW_EMPLOYEE_LIFECYCLE,
];

export const useGetManagerTypes = (
  neededPermissions: UserPermissions[] = [],
) => {
  const { user } = useRequiredAuth();
  const { hasAll: isAdmin } = usePermissions(neededPermissions);
  // FIXME: This is provisory in order to avoid an 403 error, we need to apply another solution along with backend
  const { hasAny: canQuerySubordinates } = usePermissions(
    SUBORDINATES_NEEDED_PERMISSIONS,
  );

  const {
    data: subordinates,
    isLoading,
    isFetching,
  } = useQuery(
    orgChartKeys.detailSubordinates(user.id),
    () => getUserSubordinates(user.id),
    {
      enabled: canQuerySubordinates,
      staleTime: 1000 * 60,
    },
  );

  const isFetchingSubordinates = isLoading && isFetching;
  const isManager = (subordinates?.data.length ?? 0) > 0;
  const isApprover = !isManager && !isAdmin;

  return {
    isApprover,
    isManager,
    isAdmin,
    isFetchingSubordinates,
  };
};
