// SPDX-License-Identifier: Apache-2.0
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);
};
/* eslint-disable @typescript-eslint/no-explicit-any */
import { injectable } from "tsyringe";
import { QUERY_HANDLER_METADATA, QUERY_METADATA } from "../Constants";
import Injectable from "../injectable/Injectable";
import { QueryHandlerNotFoundException } from "./error/QueryHandlerNotFoundException";
import { InvalidQueryHandlerException } from "./error/InvalidQueryHandlerException";
let QueryBus = class QueryBus {
    handlers = new Map();
    constructor() {
        const handlers = Injectable.getQueryHandlers();
        this.registerHandlers(handlers);
    }
    execute(query) {
        const queryId = this.getQueryId(query);
        const handler = this.handlers.get(queryId);
        if (!handler) {
            throw new QueryHandlerNotFoundException(queryId);
        }
        return handler.execute(query);
    }
    bind(handler, id) {
        this.handlers.set(id, handler);
    }
    getQueryId(query) {
        const { constructor: queryType } = Object.getPrototypeOf(query);
        const queryMetadata = Reflect.getMetadata(QUERY_METADATA, queryType);
        if (!queryMetadata) {
            throw new QueryHandlerNotFoundException(queryType.name);
        }
        return queryMetadata.id;
    }
    registerHandlers(handlers) {
        handlers.forEach((handler) => {
            const target = this.reflectQueryId(handler);
            if (!target) {
                throw new InvalidQueryHandlerException();
            }
            this.bind(handler, target);
        });
    }
    reflectQueryId(handler) {
        const { constructor: handlerType } = Object.getPrototypeOf(handler);
        const query = Reflect.getMetadata(QUERY_HANDLER_METADATA, handlerType);
        const queryMetadata = Reflect.getMetadata(QUERY_METADATA, query);
        return queryMetadata.id;
    }
};
QueryBus = __decorate([
    injectable(),
    __metadata("design:paramtypes", [])
], QueryBus);
export { QueryBus };
