"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.DashboardRepository = void 0;
const common_1 = require("@nestjs/common");
const dashboard_entity_1 = require("../entities/dashboard.entity");
const module_metadata_entity_1 = require("../entities/module-metadata.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 DashboardRepository = class DashboardRepository extends solid_base_repository_1.SolidBaseRepository {
    constructor(dataSource, requestContextService, securityRuleRepository) {
        super(dashboard_entity_1.Dashboard, dataSource, requestContextService, securityRuleRepository);
        this.dataSource = dataSource;
        this.requestContextService = requestContextService;
        this.securityRuleRepository = securityRuleRepository;
    }
    async upsertWithDto(createDto) {
        const moduleMetadataRepository = this.dataSource.getRepository(module_metadata_entity_1.ModuleMetadata);
        const module = await moduleMetadataRepository.findOneBy({ name: createDto.moduleUserKey });
        if (!module)
            throw new Error(`Module with key ${createDto.moduleUserKey} not found`);
        const existingDashboard = await this.findOne({
            where: { name: createDto.name },
            relations: ['dashboardVariables', 'questions', 'questions.questionSqlDatasetConfigs'],
        });
        if (existingDashboard) {
            existingDashboard.layoutJson = JSON.stringify(createDto.layoutJson ?? {});
            existingDashboard.module = module;
            existingDashboard.dashboardVariables = createDto.dashboardVariables?.map(variable => {
                const existingVar = existingDashboard.dashboardVariables.find(v => v.variableName === variable.variableName);
                if (existingVar) {
                    return Object.assign(existingVar, {
                        ...variable,
                        selectionStaticValues: JSON.stringify(variable.selectionStaticValues ?? []),
                        defaultValue: JSON.stringify(variable.defaultValue ?? []),
                    });
                }
                return {
                    ...variable,
                    selectionStaticValues: JSON.stringify(variable.selectionStaticValues ?? []),
                    defaultValue: JSON.stringify(variable.defaultValue ?? []),
                };
            }) ?? [];
            existingDashboard.questions = createDto.questions?.map(question => {
                const existingQuestion = existingDashboard.questions.find(q => q.name === question.name);
                const questionData = {
                    ...question,
                    questionSqlDatasetConfigs: question.questionSqlDatasetConfigs?.map(cfg => {
                        const existingCfg = existingQuestion?.questionSqlDatasetConfigs.find(c => c.datasetName === cfg.datasetName);
                        if (existingCfg) {
                            return Object.assign(existingCfg, {
                                ...cfg,
                                options: JSON.stringify(cfg.options ?? {}),
                            });
                        }
                        return {
                            ...cfg,
                            options: JSON.stringify(cfg.options ?? {}),
                        };
                    }) ?? [],
                };
                return existingQuestion ? Object.assign(existingQuestion, questionData) : questionData;
            }) ?? [];
            return this.save(existingDashboard);
        }
        const dashboardData = {
            ...createDto,
            module,
            layoutJson: JSON.stringify(createDto.layoutJson ?? {}),
            dashboardVariables: createDto.dashboardVariables?.map(variable => ({
                ...variable,
                selectionStaticValues: JSON.stringify(variable.selectionStaticValues ?? []),
                defaultValue: JSON.stringify(variable.defaultValue ?? []),
            })),
            questions: createDto.questions?.map(question => ({
                ...question,
                questionSqlDatasetConfigs: question.questionSqlDatasetConfigs?.map(cfg => ({
                    ...cfg,
                    options: JSON.stringify(cfg.options ?? {}),
                })),
            })),
        };
        const newDashboard = this.create(dashboardData);
        return this.save(newDashboard);
    }
};
exports.DashboardRepository = DashboardRepository;
exports.DashboardRepository = DashboardRepository = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [typeorm_1.DataSource,
        request_context_service_1.RequestContextService,
        security_rule_repository_1.SecurityRuleRepository])
], DashboardRepository);
//# sourceMappingURL=dashboard.repository.js.map