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

function useUnregisterEntityDialogState(entity) {
  const catalogApi = useApi(catalogApiRef);
  const locationRef = entity.metadata.annotations?.[ANNOTATION_ORIGIN_LOCATION];
  const uid = entity.metadata.uid;
  const isBootstrap = locationRef === "bootstrap:bootstrap";
  const prerequisites = useAsync(async () => {
    const locationPromise = catalogApi.getLocationByRef(locationRef);
    let colocatedEntitiesPromise;
    if (!locationRef) {
      colocatedEntitiesPromise = Promise.resolve([]);
    } else {
      const locationAnnotationFilter = `metadata.annotations.${ANNOTATION_ORIGIN_LOCATION}`;
      colocatedEntitiesPromise = catalogApi.getEntities({
        filter: { [locationAnnotationFilter]: locationRef },
        fields: [
          "kind",
          "metadata.uid",
          "metadata.name",
          "metadata.namespace"
        ]
      }).then((response) => response.items);
    }
    return Promise.all([locationPromise, colocatedEntitiesPromise]).then(
      ([location2, colocatedEntities2]) => ({
        location: location2,
        colocatedEntities: colocatedEntities2
      })
    );
  }, [catalogApi, entity]);
  const unregisterLocation = useCallback(
    async function unregisterLocationFn() {
      const { location: location2 } = prerequisites.value;
      await catalogApi.removeLocationById(location2.id);
    },
    [catalogApi, prerequisites]
  );
  const deleteEntity = useCallback(
    async function deleteEntityFn() {
      await catalogApi.removeEntityByUid(uid);
    },
    [catalogApi, uid]
  );
  if (isBootstrap) {
    return { type: "bootstrap", location: locationRef, deleteEntity };
  }
  const { loading, error, value } = prerequisites;
  if (loading) {
    return { type: "loading" };
  } else if (error) {
    return { type: "error", error };
  }
  const { location, colocatedEntities } = value;
  if (!location) {
    return { type: "only-delete", deleteEntity };
  }
  return {
    type: "unregister",
    location: locationRef,
    colocatedEntities: colocatedEntities.map(getCompoundEntityRef),
    unregisterLocation,
    deleteEntity
  };
}

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