"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var SecurityRuleSubscriber_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecurityRuleSubscriber = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const fs = __importStar(require("fs/promises"));
const constants_1 = require("../constants");
const model_metadata_entity_1 = require("../entities/model-metadata.entity");
const security_rule_entity_1 = require("../entities/security-rule.entity");
const module_metadata_helper_service_1 = require("../helpers/module-metadata-helper.service");
const security_rule_repository_1 = require("../repository/security-rule.repository");
const typeorm_2 = require("typeorm");
let SecurityRuleSubscriber = SecurityRuleSubscriber_1 = class SecurityRuleSubscriber {
    constructor(dataSource, moduleMetadataHelperService, securityRuleRepo) {
        this.dataSource = dataSource;
        this.moduleMetadataHelperService = moduleMetadataHelperService;
        this.securityRuleRepo = securityRuleRepo;
        this.logger = new common_1.Logger(SecurityRuleSubscriber_1.name);
        this.dataSource.subscribers.push(this);
    }
    listenTo() {
        return security_rule_entity_1.SecurityRule;
    }
    async afterInsert(event) {
        await this.saveSecurityRules(event);
    }
    async afterUpdate(event) {
        await this.saveSecurityRules(event);
    }
    async saveSecurityRules(event) {
        const securityRule = event.entity;
        const modelMetadata = event.entity.modelMetadata;
        if (!modelMetadata) {
            this.logger.error(`Model metadata not found for security rule with id ${event.entity.id}`);
            return;
        }
        const modelMetadataRepo = this.dataSource.getRepository(model_metadata_entity_1.ModelMetadata);
        const populatedModelMetadata = await modelMetadataRepo.findOne({
            where: {
                id: modelMetadata.id
            },
            relations: {
                module: true,
            }
        });
        if (populatedModelMetadata.module.name === constants_1.SOLID_CORE_MODULE_NAME) {
            return;
        }
        const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(populatedModelMetadata.module.name);
        try {
            await fs.access(filePath);
        }
        catch (error) {
            this.logger.error(`File not found at path: ${filePath}`);
            return;
        }
        const metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);
        if (metaData.securityRules) {
            const securityRuleIndex = metaData.securityRules?.findIndex((ruleFromFile) => ruleFromFile.name === securityRule.name);
            const { id, roleId, modelMetadataId, ...requiredDto } = await this.securityRuleRepo.toDto(securityRule);
            metaData.securityRules[securityRuleIndex] = { ...requiredDto, securityRuleConfig: JSON.parse(securityRule.securityRuleConfig) };
        }
        else {
            const securityRules = [];
            const { id, roleId, modelMetadataId, ...requiredDto } = await this.securityRuleRepo.toDto(securityRule);
            securityRules.push({ ...requiredDto, securityRuleConfig: JSON.parse(securityRule.securityRuleConfig) });
            metaData.securityRules = securityRules;
        }
        const updatedContent = JSON.stringify(metaData, null, 2);
        await fs.writeFile(filePath, updatedContent);
    }
};
exports.SecurityRuleSubscriber = SecurityRuleSubscriber;
exports.SecurityRuleSubscriber = SecurityRuleSubscriber = SecurityRuleSubscriber_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectDataSource)()),
    __metadata("design:paramtypes", [typeorm_2.DataSource,
        module_metadata_helper_service_1.ModuleMetadataHelperService,
        security_rule_repository_1.SecurityRuleRepository])
], SecurityRuleSubscriber);
//# sourceMappingURL=security-rule.subscriber.js.map