"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 CacheInvalidationSubscriber_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheInvalidationSubscriber = void 0;
const typeorm_1 = require("typeorm");
const common_1 = require("@nestjs/common");
const cache_invalidation_service_1 = require("./cache-invalidation.service");
let CacheInvalidationSubscriber = CacheInvalidationSubscriber_1 = class CacheInvalidationSubscriber {
    constructor() {
        this.logger = new common_1.Logger(CacheInvalidationSubscriber_1.name);
    }
    afterInsert(event) {
        this.handleEntityChange('insert', event.entity);
    }
    afterUpdate(event) {
        this.handleEntityChange('update', event.entity);
    }
    afterRemove(event) {
        this.handleEntityChange('remove', event.entity);
    }
    handleEntityChange(operation, entity) {
        if (!entity) {
            return;
        }
        const entityType = this.getEntityType(entity);
        if (!entityType) {
            return;
        }
        const context = this.extractContext(entity, entityType);
        const service = cache_invalidation_service_1.CacheInvalidationService.getInstance();
        if (!service) {
            this.logger.warn('CacheInvalidationService not initialized, skipping invalidation');
            return;
        }
        service.invalidateEntity(entityType, context).catch((err) => {
            this.logger.error(`Cache invalidation failed for ${entityType}: ${err.message}`);
        });
    }
    getEntityType(entity) {
        const entityName = entity.constructor?.name;
        switch (entityName) {
            case 'Session':
                return 'session';
            case 'SessionInput':
                return 'session_input';
            case 'AIAction':
                return 'ai_action';
            case 'ExecutionLog':
                return 'execution_log';
            case 'ContextTemplate':
                return 'context_template';
            case 'SystemPrompt':
                return 'system_prompt';
            case 'CustomSnippet':
                return 'custom_snippet';
            case 'ContextSnippet':
                return 'context_snippet';
            case 'CustomVariable':
                return 'custom_variable';
            case 'Project':
                return 'project';
            case 'ToolHook':
                return 'tool_hook';
            case 'McpConfig':
                return 'mcp_config';
            case 'SubAgent':
                return 'sub_agent';
            case 'ApplicationState':
                return 'application_state';
            case 'LlmCallLog':
                return 'llm_call_log';
            default:
                return null;
        }
    }
    extractContext(entity, entityType) {
        const context = {};
        switch (entityType) {
            case 'session':
                context.sessionId = entity.id;
                break;
            case 'session_input':
                context.sessionId = entity.session_id;
                break;
            case 'ai_action':
                context.sessionId =
                    entity.sessionInput?.session_id || entity.session_id;
                break;
            case 'execution_log':
                context.sessionId =
                    entity.aiAction?.sessionInput?.session_id ||
                        entity.sessionInput?.session_id ||
                        entity.session_id;
                break;
            case 'context_template':
                context.isDefaultChanged =
                    entity.is_default_initial || entity.is_default_followup;
                break;
            case 'system_prompt':
                context.isDefaultChanged = entity.is_default;
                break;
            case 'application_state':
                context.stateKey = entity.key;
                break;
        }
        return context;
    }
};
exports.CacheInvalidationSubscriber = CacheInvalidationSubscriber;
exports.CacheInvalidationSubscriber = CacheInvalidationSubscriber = CacheInvalidationSubscriber_1 = __decorate([
    (0, typeorm_1.EventSubscriber)()
], CacheInvalidationSubscriber);
//# sourceMappingURL=cache-invalidation.subscriber.js.map