'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var catalogModel = require('@backstage/catalog-model');
var pluginCatalogNode = require('@backstage/plugin-catalog-node');
var pluginScaffolderCommon = require('@backstage/plugin-scaffolder-common');
var backendPluginApi = require('@backstage/backend-plugin-api');
var alpha = require('@backstage/plugin-catalog-node/alpha');

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
class ScaffolderEntitiesProcessor {
  constructor() {
    __publicField(this, "validators", [pluginScaffolderCommon.templateEntityV1beta3Validator]);
  }
  getProcessorName() {
    return "ScaffolderEntitiesProcessor";
  }
  async validateEntityKind(entity) {
    for (const validator of this.validators) {
      if (await validator.check(entity)) {
        return true;
      }
    }
    return false;
  }
  async postProcessEntity(entity, _location, emit) {
    const selfRef = catalogModel.getCompoundEntityRef(entity);
    if (entity.apiVersion === "scaffolder.backstage.io/v1beta3" && entity.kind === "Template") {
      const template = entity;
      const target = template.spec.owner;
      if (target) {
        const targetRef = catalogModel.parseEntityRef(target, {
          defaultKind: "Group",
          defaultNamespace: selfRef.namespace
        });
        emit(
          pluginCatalogNode.processingResult.relation({
            source: selfRef,
            type: catalogModel.RELATION_OWNED_BY,
            target: {
              kind: targetRef.kind,
              namespace: targetRef.namespace,
              name: targetRef.name
            }
          })
        );
        emit(
          pluginCatalogNode.processingResult.relation({
            source: {
              kind: targetRef.kind,
              namespace: targetRef.namespace,
              name: targetRef.name
            },
            type: catalogModel.RELATION_OWNER_OF,
            target: selfRef
          })
        );
      }
    }
    return entity;
  }
}

const catalogModuleScaffolderEntityModel = backendPluginApi.createBackendModule({
  pluginId: "catalog",
  moduleId: "scaffolder-entity-model",
  register(env) {
    env.registerInit({
      deps: {
        catalog: alpha.catalogProcessingExtensionPoint
      },
      async init({ catalog }) {
        catalog.addProcessor(new ScaffolderEntitiesProcessor());
      }
    });
  }
});

exports.ScaffolderEntitiesProcessor = ScaffolderEntitiesProcessor;
exports["default"] = catalogModuleScaffolderEntityModel;
//# sourceMappingURL=index.cjs.js.map
