"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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var ContextSnippetsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextSnippetsService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const core_entities_1 = require("../core-entities");
const context_generation_service_1 = require("../context-generation/context-generation.service");
const custom_variables_service_1 = require("../custom-variables/custom-variables.service");
let ContextSnippetsService = ContextSnippetsService_1 = class ContextSnippetsService {
    constructor(contextSnippetsRepository, contextGenerationService, customVariablesService) {
        this.contextSnippetsRepository = contextSnippetsRepository;
        this.contextGenerationService = contextGenerationService;
        this.customVariablesService = customVariablesService;
        this.logger = new common_1.Logger(ContextSnippetsService_1.name);
    }
    async create(createDto) {
        const existing = await this.contextSnippetsRepository.findOneBy({
            handle: createDto.handle,
        });
        if (existing) {
            throw new common_1.BadRequestException(`A context snippet with the handle "${createDto.handle}" already exists.`);
        }
        const snippet = this.contextSnippetsRepository.create(createDto);
        return this.contextSnippetsRepository.save(snippet);
    }
    async findAll() {
        return this.contextSnippetsRepository.find({ order: { handle: 'ASC' } });
    }
    async findOne(id) {
        const snippet = await this.contextSnippetsRepository.findOneBy({ id });
        if (!snippet) {
            throw new common_1.NotFoundException(`ContextSnippet with ID "${id}" not found`);
        }
        return snippet;
    }
    async findByHandle(handle) {
        const snippet = await this.contextSnippetsRepository.findOneBy({ handle });
        if (!snippet) {
            throw new common_1.NotFoundException(`ContextSnippet with handle "${handle}" not found`);
        }
        return snippet;
    }
    async update(id, updateDto) {
        const snippet = await this.findOne(id);
        if (updateDto.handle && updateDto.handle !== snippet.handle) {
            const existing = await this.contextSnippetsRepository.findOneBy({
                handle: updateDto.handle,
            });
            if (existing) {
                throw new common_1.BadRequestException(`A context snippet with the handle "${updateDto.handle}" already exists.`);
            }
        }
        this.contextSnippetsRepository.merge(snippet, updateDto);
        return this.contextSnippetsRepository.save(snippet);
    }
    async remove(id) {
        const snippet = await this.findOne(id);
        await this.contextSnippetsRepository.remove(snippet);
    }
    async preview(dto) {
        try {
            const enabledVariables = await this.customVariablesService.findAllEnabled();
            const variableMap = enabledVariables.reduce((acc, curr) => {
                acc[curr.key] = curr.value;
                return acc;
            }, {});
            const data = {
                VAR: variableMap,
            };
            const rendered_text = await this.contextGenerationService.render(dto.template_content, data);
            return { rendered_text };
        }
        catch (error) {
            this.logger.error(`Error rendering snippet preview: ${error.message}`);
            return {
                rendered_text: '',
                error: error.message,
            };
        }
    }
};
exports.ContextSnippetsService = ContextSnippetsService;
exports.ContextSnippetsService = ContextSnippetsService = ContextSnippetsService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(core_entities_1.ContextSnippet)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        context_generation_service_1.ContextGenerationService,
        custom_variables_service_1.CustomVariablesService])
], ContextSnippetsService);
//# sourceMappingURL=context-snippets.service.js.map