import { parseEntityRef } from '@backstage/catalog-model';
import { useApi } from '@backstage/core-plugin-api';
import useAsync from 'react-use/esm/useAsync';
import { catalogApiRef } from '../api.esm.js';

function useRelatedEntities(entity, relationFilter) {
  const filterByTypeLower = relationFilter?.type?.toLocaleLowerCase("en-US");
  const filterByKindLower = relationFilter?.kind?.toLocaleLowerCase("en-US");
  const catalogApi = useApi(catalogApiRef);
  const {
    loading,
    value: entities,
    error
  } = useAsync(async () => {
    const relations = entity.relations?.filter(
      (r) => (!filterByTypeLower || r.type.toLocaleLowerCase("en-US") === filterByTypeLower) && (!filterByKindLower || parseEntityRef(r.targetRef).kind === filterByKindLower)
    );
    if (!relations?.length) {
      return [];
    }
    const { items } = await catalogApi.getEntitiesByRefs({
      entityRefs: relations.map((r) => r.targetRef)
    });
    return items.filter((x) => Boolean(x));
  }, [entity, filterByTypeLower, filterByKindLower]);
  return {
    entities,
    loading,
    error
  };
}

export { useRelatedEntities };
//# sourceMappingURL=useRelatedEntities.esm.js.map
