"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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScheduledJobRepository = void 0;
const common_1 = require("@nestjs/common");
const module_metadata_entity_1 = require("../entities/module-metadata.entity");
const scheduled_job_entity_1 = require("../entities/scheduled-job.entity");
const request_context_service_1 = require("../services/request-context.service");
const typeorm_1 = require("typeorm");
const security_rule_repository_1 = require("./security-rule.repository");
const solid_base_repository_1 = require("./solid-base.repository");
let ScheduledJobRepository = class ScheduledJobRepository extends solid_base_repository_1.SolidBaseRepository {
    constructor(dataSource, requestContextService, securityRuleRepository) {
        super(scheduled_job_entity_1.ScheduledJob, dataSource, requestContextService, securityRuleRepository);
        this.dataSource = dataSource;
        this.requestContextService = requestContextService;
        this.securityRuleRepository = securityRuleRepository;
    }
    async toDto(scheduledJob) {
        let populatedScheduledJob = scheduledJob;
        if (!scheduledJob.module) {
            populatedScheduledJob = await this.findOne({
                where: {
                    id: scheduledJob.id,
                },
                relations: {
                    module: true,
                },
            });
        }
        if (!populatedScheduledJob.module) {
            throw new Error(`Module not found for scheduled job ID ${populatedScheduledJob.id}`);
        }
        return {
            scheduleName: populatedScheduledJob.scheduleName,
            isActive: populatedScheduledJob.isActive,
            frequency: populatedScheduledJob.frequency,
            startTime: populatedScheduledJob.startTime,
            endTime: populatedScheduledJob.endTime,
            startDate: populatedScheduledJob.startDate,
            endDate: populatedScheduledJob.endDate,
            dayOfMonth: populatedScheduledJob.dayOfMonth,
            lastRunAt: populatedScheduledJob.lastRunAt,
            nextRunAt: populatedScheduledJob.nextRunAt,
            dayOfWeek: populatedScheduledJob.dayOfWeek,
            job: populatedScheduledJob.job,
            moduleUserKey: populatedScheduledJob.module.name,
            moduleId: populatedScheduledJob.module.id,
            cronExpression: populatedScheduledJob.cronExpression,
        };
    }
    async upsertWithDto(dto) {
        const moduleRepo = this.dataSource.getRepository(module_metadata_entity_1.ModuleMetadata);
        const moduleEntity = await moduleRepo.findOne({
            where: { name: dto.moduleUserKey },
        });
        if (!moduleEntity) {
            throw new Error(`Module with userKey ${dto.moduleUserKey} not found`);
        }
        const jobData = {
            ...dto,
            module: moduleEntity,
        };
        const existing = await this.findOne({
            where: { scheduleName: dto.scheduleName },
        });
        if (existing) {
            const merged = this.merge(existing, jobData);
            this.logger.debug(`Updating scheduled job: ${dto.scheduleName}`);
            return this.save(merged);
        }
        else {
            this.logger.debug(`Creating scheduled job: ${dto.scheduleName}`);
            return this.save(this.create(jobData));
        }
    }
};
exports.ScheduledJobRepository = ScheduledJobRepository;
exports.ScheduledJobRepository = ScheduledJobRepository = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [typeorm_1.DataSource,
        request_context_service_1.RequestContextService,
        security_rule_repository_1.SecurityRuleRepository])
], ScheduledJobRepository);
//# sourceMappingURL=scheduled-job.repository.js.map