"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 ScheduledJobSubscriber_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScheduledJobSubscriber = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const fs = __importStar(require("fs/promises"));
const module_metadata_entity_1 = require("../entities/module-metadata.entity");
const scheduled_job_entity_1 = require("../entities/scheduled-job.entity");
const module_metadata_helper_service_1 = require("../helpers/module-metadata-helper.service");
const scheduled_job_repository_1 = require("../repository/scheduled-job.repository");
const typeorm_2 = require("typeorm");
let ScheduledJobSubscriber = ScheduledJobSubscriber_1 = class ScheduledJobSubscriber {
    constructor(dataSource, moduleMetadataHelperService, scheduledJobRepo) {
        this.dataSource = dataSource;
        this.moduleMetadataHelperService = moduleMetadataHelperService;
        this.scheduledJobRepo = scheduledJobRepo;
        this.logger = new common_1.Logger(ScheduledJobSubscriber_1.name);
        this.ignoredUpdateFields = [
            "lastRunAt",
            "nextRunAt",
            "updatedAt",
        ];
        this.dataSource.subscribers.push(this);
    }
    listenTo() {
        return scheduled_job_entity_1.ScheduledJob;
    }
    async afterInsert(event) {
        if (!event.entity) {
            this.logger.debug('No schedule Job entity found in the  afterInsert method');
            return;
        }
        await this.updateMetadata(event.entity, event.queryRunner.manager);
    }
    async afterUpdate(event) {
        if (!event.databaseEntity) {
            this.logger.debug('No schedule Job entity found in the  afterUpdate method');
            return;
        }
        const changedProps = (event.updatedColumns ?? []).map((c) => c.propertyName);
        const onlyIgnoredChanged = changedProps.every((p) => this.ignoredUpdateFields.includes(p));
        if (onlyIgnoredChanged) {
            this.logger.debug(`Skipping metadata update for ScheduledJob#${event.databaseEntity.id}; only ignored fields changed: ${changedProps.join(", ")}`);
            return;
        }
        await this.updateMetadata(event.databaseEntity, event.queryRunner.manager);
    }
    async afterRemove(event) {
        await this.removeMetadata(event);
    }
    async removeMetadata(event) {
        const jobEntity = event.entity;
        const moduleMetadata = jobEntity?.module;
        if (!moduleMetadata) {
            this.logger.error(`Module metadata not found for scheduled job with ID ${jobEntity?.id}`);
            return;
        }
        const moduleMetadataRepo = this.dataSource.getRepository(module_metadata_entity_1.ModuleMetadata);
        const populatedModuleMetadata = await moduleMetadataRepo.findOne({
            where: { id: moduleMetadata.id },
        });
        if (!populatedModuleMetadata) {
            this.logger.error(`Could not find ModuleMetadata with ID ${moduleMetadata.id}`);
            return;
        }
        const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(populatedModuleMetadata.name);
        try {
            await fs.access(filePath);
        }
        catch {
            this.logger.error(`Metadata file not found: ${filePath}`);
            return;
        }
        const metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);
        const jobName = jobEntity.scheduleName;
        const existingIndex = metaData.scheduledJobs.findIndex((job) => job.scheduleName === jobName);
        if (existingIndex !== -1) {
            metaData.scheduledJobs.splice(existingIndex, 1);
            this.logger.log(`Removed scheduled job ${jobName} from metadata`);
        }
        const updatedContent = JSON.stringify(metaData, null, 2);
        await fs.writeFile(filePath, updatedContent);
        this.logger.log(`Updated scheduledJobs in ${filePath}`);
    }
    async updateMetadata(jobEntity, entityManager) {
        const populatedScheduleJob = await entityManager.findOne(scheduled_job_entity_1.ScheduledJob, {
            where: { id: jobEntity.id },
            relations: ['module'],
        });
        if (!populatedScheduleJob) {
            throw new Error(`ScheduleJob not found for id ${jobEntity.id}`);
        }
        const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(populatedScheduleJob.module?.name);
        try {
            await fs.access(filePath);
        }
        catch {
            this.logger.error(`Metadata file not found: ${filePath}`);
            return;
        }
        const metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);
        if (!metaData.scheduledJobs) {
            metaData.scheduledJobs = [];
        }
        const jobName = jobEntity.scheduleName;
        const existingIndex = metaData.scheduledJobs.findIndex((job) => job.scheduleName === jobName);
        const jobDto = await this.scheduledJobRepo.toDto(populatedScheduleJob);
        const { moduleId, lastRunAt, nextRunAt, ...dtoToWrite } = jobDto;
        if (existingIndex !== -1) {
            metaData.scheduledJobs[existingIndex] = dtoToWrite;
            this.logger.log(`Updated scheduled job ${jobName} in metadata`);
        }
        else {
            metaData.scheduledJobs.push(dtoToWrite);
            this.logger.log(`Added scheduled job ${jobName} to metadata`);
        }
        const updatedContent = JSON.stringify(metaData, null, 2);
        await fs.writeFile(filePath, updatedContent);
        this.logger.log(`Updated scheduledJobs in ${filePath}`);
    }
};
exports.ScheduledJobSubscriber = ScheduledJobSubscriber;
exports.ScheduledJobSubscriber = ScheduledJobSubscriber = ScheduledJobSubscriber_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectDataSource)()),
    __metadata("design:paramtypes", [typeorm_2.DataSource,
        module_metadata_helper_service_1.ModuleMetadataHelperService,
        scheduled_job_repository_1.ScheduledJobRepository])
], ScheduledJobSubscriber);
//# sourceMappingURL=scheduled-job.subscriber.js.map