import { RELATION_OWNED_BY, stringifyEntityRef } from '@backstage/catalog-model';
import { useApi, identityApiRef } from '@backstage/core-plugin-api';
import { useMemo } from 'react';
import useAsync from 'react-use/esm/useAsync';
import { getEntityRelations } from '../utils/getEntityRelations.esm.js';

function useEntityOwnership() {
  const identityApi = useApi(identityApiRef);
  const { loading, value: refs } = useAsync(
    async () => {
      const { ownershipEntityRefs } = await identityApi.getBackstageIdentity();
      return ownershipEntityRefs;
    },
    // load only on mount
    []
  );
  const isOwnedEntity = useMemo(() => {
    const myOwnerRefs = new Set(refs ?? []);
    return (entity) => {
      const entityOwnerRefs = getEntityRelations(entity, RELATION_OWNED_BY).map(
        stringifyEntityRef
      );
      for (const ref of entityOwnerRefs) {
        if (myOwnerRefs.has(ref)) {
          return true;
        }
      }
      return false;
    };
  }, [refs]);
  return { loading, isOwnedEntity };
}

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