"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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListOfValuesService = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const crud_service_1 = require("./crud.service");
const fs = __importStar(require("fs/promises"));
const module_metadata_helper_service_1 = require("../helpers/module-metadata-helper.service");
const list_of_values_mapper_1 = require("../mappers/list-of-values-mapper");
const list_of_values_repository_1 = require("../repository/list-of-values.repository");
let ListOfValuesService = class ListOfValuesService extends crud_service_1.CRUDService {
    constructor(entityManager, repo, moduleRef, moduleMetadataHelperService, listOfValuesMapper) {
        super(entityManager, repo, 'listOfValues', 'solid-core', moduleRef);
        this.entityManager = entityManager;
        this.repo = repo;
        this.moduleRef = moduleRef;
        this.moduleMetadataHelperService = moduleMetadataHelperService;
        this.listOfValuesMapper = listOfValuesMapper;
    }
    async findOneByValueAndType(lovValue, lovType) {
        return await this.repo.findOne({
            where: {
                value: lovValue,
                type: lovType,
            },
        });
    }
    async findAll() {
        return await this.repo.find();
    }
    async upsert(updateListOfValuesDto) {
        const existingListOfValue = await this.repo.findOne({
            where: {
                value: updateListOfValuesDto.value,
                type: updateListOfValuesDto.type,
            }
        });
        if (existingListOfValue) {
            const updatedListOfValuesDto = { ...existingListOfValue, ...updateListOfValuesDto };
            return this.repo.save(updatedListOfValuesDto);
        }
        else {
            const listOfValue = this.repo.create(updateListOfValuesDto);
            return this.repo.save(listOfValue);
        }
    }
    async saveListofValuesToConfig(entity) {
        if (!entity) {
            this.logger.debug('No entity found in the ListofValuesSubscriber saveListofvalueToConfig method');
            return;
        }
        const listofvalue = entity;
        const moduleMetadata = entity.module;
        if (!moduleMetadata) {
            throw new Error(`Module metadata not found for listofvalue id ${entity.id}`);
        }
        const { filePath, metaData } = await this.getConfigFileDetails(moduleMetadata.name);
        if (!filePath || !metaData) {
            throw new Error(`Configuration details not found for module: ${moduleMetadata.name}`);
        }
        await this.writeToConfig(metaData, listofvalue, filePath);
    }
    async updateListofValuesToConfig(oldentity, entity) {
        if (!entity) {
            this.logger.debug('No entity found in the ListofValuesSubscriber saveListofvalueToConfig method');
            return;
        }
        const oldlistofvalue = oldentity;
        const listofvalue = entity;
        const moduleMetadata = entity.module;
        if (!moduleMetadata) {
            throw new Error(`Module metadata not found for listofvalue id ${entity.id}`);
        }
        const { filePath, metaData } = await this.getConfigFileDetails(moduleMetadata.name);
        if (!filePath || !metaData) {
            throw new Error(`Configuration details not found for module: ${moduleMetadata.name}`);
        }
        await this.updateToConfig(metaData, oldlistofvalue, listofvalue, filePath);
    }
    async deleteListOfValuesFromConfig(entity) {
        if (!entity) {
            this.logger.debug('No entity found in the ListofValuesSubscriber saveListofvalueToConfig method');
            return;
        }
        const listofvalue = entity;
        const moduleMetadata = entity.module;
        if (!moduleMetadata) {
            throw new Error(`Module metadata not found for listofvalue id ${entity.id}`);
        }
        const { filePath, metaData } = await this.getConfigFileDetails(moduleMetadata.name);
        if (!filePath || !metaData) {
            throw new Error(`Configuration details not found for module: ${moduleMetadata.name}`);
        }
        await this.deleteFromConfig(metaData, listofvalue, filePath);
    }
    async getConfigFileDetails(moduleName) {
        const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(moduleName);
        try {
            await fs.access(filePath);
        }
        catch (error) {
            throw new Error(`Configuration file not found for module: ${moduleName}`);
        }
        const metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);
        return { filePath, metaData };
    }
    async writeToConfig(metaData, listofvalues, filePath) {
        const dto = await this.listOfValuesMapper.toDto(listofvalues);
        if (!Array.isArray(metaData.listOfValues)) {
            metaData.listOfValues = [];
        }
        const existingIndex = metaData.listOfValues.findIndex((item) => item.type === dto.type &&
            item.value === dto.value &&
            item.module === dto.module);
        if (existingIndex !== -1) {
            metaData.listOfValues[existingIndex] = dto;
        }
        else {
            if (metaData.listOfValues.length === 0) {
                metaData.listOfValues.push(dto);
            }
            else {
                metaData.listOfValues.unshift(dto);
            }
        }
        const updatedContent = JSON.stringify(metaData, null, 2);
        await fs.writeFile(filePath, updatedContent);
    }
    async updateToConfig(metaData, oldlistofvalues, listofvalues, filePath) {
        const newvalue = await this.listOfValuesMapper.toDto(listofvalues);
        const oldvalue = await this.listOfValuesMapper.toDto(oldlistofvalues);
        if (!Array.isArray(metaData.listOfValues)) {
            metaData.listOfValues = [];
        }
        const searchType = oldvalue.type || newvalue.type;
        const searchValue = oldvalue.value || newvalue.value;
        const searchModule = oldvalue.module || newvalue.module;
        const existingIndex = metaData.listOfValues.findIndex((item) => item.type === searchType && item.value === searchValue && item.module === searchModule);
        if (existingIndex !== -1) {
            metaData.listOfValues[existingIndex] = newvalue;
        }
        const updatedContent = JSON.stringify(metaData, null, 2);
        await fs.writeFile(filePath, updatedContent);
    }
    async deleteFromConfig(metaData, listofvalues, filePath) {
        const dto = await this.listOfValuesMapper.toDto(listofvalues);
        if (!Array.isArray(metaData.listOfValues)) {
            metaData.listOfValues = [];
        }
        const existingIndex = metaData.listOfValues.findIndex((item) => item.type === dto.type &&
            item.value === dto.value &&
            item.module === dto.module);
        if (existingIndex !== -1) {
            metaData.listOfValues.splice(existingIndex, 1);
            this.logger.debug(`Deleted LOV ${dto.type}:${dto.value} (module ${dto.module}) from config`);
        }
        else {
            this.logger.warn(`LOV ${dto.type}:${dto.value} (module ${dto.module}) not found in config during delete`);
        }
        const updatedContent = JSON.stringify(metaData, null, 2);
        await fs.writeFile(filePath, updatedContent);
    }
};
exports.ListOfValuesService = ListOfValuesService;
exports.ListOfValuesService = ListOfValuesService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectEntityManager)()),
    __metadata("design:paramtypes", [typeorm_2.EntityManager,
        list_of_values_repository_1.ListOfValuesRepository,
        core_1.ModuleRef,
        module_metadata_helper_service_1.ModuleMetadataHelperService,
        list_of_values_mapper_1.ListOfValuesMapper])
], ListOfValuesService);
//# sourceMappingURL=list-of-values.service.js.map