"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const api_token_1 = require("../../types/models/api-token");
const metric_events_1 = require("../../metric-events");
class EventService {
    constructor({ eventStore, featureTagStore, }, { getLogger, eventBus }) {
        this.logger = getLogger('services/event-service.ts');
        this.eventStore = eventStore;
        this.featureTagStore = featureTagStore;
        this.eventBus = eventBus;
    }
    async getEvents() {
        const totalEvents = await this.eventStore.count();
        const events = await this.eventStore.getEvents();
        return {
            events,
            totalEvents,
        };
    }
    async searchEvents(search) {
        const totalEvents = await this.eventStore.filteredCount(search);
        const events = await this.eventStore.searchEvents(search);
        return {
            events,
            totalEvents,
        };
    }
    async onEvent(eventName, listener) {
        return this.eventStore.on(eventName, listener);
    }
    async enhanceEventsWithTags(events) {
        const featureNamesSet = new Set();
        for (const event of events) {
            if (event.featureName && !event.tags) {
                featureNamesSet.add(event.featureName);
            }
        }
        const featureTagsMap = new Map();
        const allTagsInFeatures = await this.featureTagStore.getAllByFeatures(Array.from(featureNamesSet));
        for (const tag of allTagsInFeatures) {
            const featureTags = featureTagsMap.get(tag.featureName) || [];
            featureTags.push({ value: tag.tagValue, type: tag.tagType });
            featureTagsMap.set(tag.featureName, featureTags);
        }
        for (const event of events) {
            if (event.featureName && !event.tags) {
                event.tags = featureTagsMap.get(event.featureName);
            }
        }
        return events;
    }
    isAdminToken(user) {
        return user?.type === api_token_1.ApiTokenType.ADMIN;
    }
    async storeEvent(event) {
        return this.storeEvents([event]);
    }
    async storeEvents(events) {
        let enhancedEvents = events;
        for (const enhancer of [this.enhanceEventsWithTags.bind(this)]) {
            enhancedEvents = await enhancer(enhancedEvents);
        }
        return this.eventStore.batchStore(enhancedEvents);
    }
    async setEventCreatedByUserId() {
        const updated = await this.eventStore.setCreatedByUserId(100);
        if (updated !== undefined) {
            this.eventBus.emit(metric_events_1.EVENTS_CREATED_BY_PROCESSED, {
                updated,
            });
        }
    }
}
exports.default = EventService;
//# sourceMappingURL=event-service.js.map