"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DomainSubscriber = void 0;
const typeorm_1 = require("typeorm");
const uuid_1 = require("uuid");
const operato_license_checker_1 = require("@things-factory/operato-license-checker");
const shell_1 = require("@things-factory/shell");
const license_error_1 = require("../errors/license-error");
const domain_secret_1 = require("../service/domain-secret/domain-secret");
let DomainSubscriber = class DomainSubscriber {
    listenTo() {
        return shell_1.Domain;
    }
    /**
     * Called before domain insertion.
     */
    async afterInsert(event) {
        var entityManager = event.manager;
        if ((0, operato_license_checker_1.getValidity)()) {
            //1. check domain count is over licensed quantity or not
            var domain = event.entity;
            var count = (await entityManager
                .createQueryBuilder()
                .select('domain')
                .from(domain_secret_1.DomainSecret, 'secret')
                .where('domain_id = :domainId', { domainId: domain.id })
                .getCount()) + 1;
            //2. create new token to domain and save domain-secret
            if ((0, operato_license_checker_1.checkDomain)(count)) {
                var domain = event.entity;
                var domainSecret = new domain_secret_1.DomainSecret();
                domainSecret.id = (0, uuid_1.v4)();
                domainSecret.domain = domain.domain;
                var hash = (0, operato_license_checker_1.doSomething)({ secId: domainSecret.id, id: domain.id });
                domainSecret.secret = hash;
                await entityManager.save(domainSecret);
            }
            else {
                throw new license_error_1.LicenseError({
                    errorCode: license_error_1.LicenseError.ERROR_CODES.VERIFICATION_ERROR
                });
            }
        }
    }
    /**
     * Called after entity is removed.
     */
    async afterRemove(event) {
        var entityManager = event.manager;
        await entityManager.query(`delete 
             from domain_secrets
            where domain_id not in (select id from domains)`);
    }
};
DomainSubscriber = __decorate([
    (0, typeorm_1.EventSubscriber)()
], DomainSubscriber);
exports.DomainSubscriber = DomainSubscriber;
//# sourceMappingURL=domain-subscriber.js.map