// 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 { COMMAND_HANDLER_METADATA, COMMAND_METADATA } from "../Constants";
import Injectable from "../injectable/Injectable";
import { CommandHandlerNotFoundException } from "./error/CommandHandlerNotFoundException";
import { InvalidCommandHandlerException } from "./error/InvalidCommandHandlerException";
let CommandBus = class CommandBus {
    handlers = new Map();
    constructor() {
        const handlers = Injectable.getCommandHandlers();
        this.registerHandlers(handlers);
    }
    execute(command) {
        const commandId = this.getCommandId(command);
        const handler = this.handlers.get(commandId);
        if (!handler) {
            throw new CommandHandlerNotFoundException(commandId);
        }
        // Has to be casted to return type as it its inferred based off the parameter
        return handler.execute(command);
    }
    bind(handler, id) {
        this.handlers.set(id, handler);
    }
    getCommandId(command) {
        const { constructor: commandType } = Object.getPrototypeOf(command);
        const commandMetadata = Reflect.getMetadata(COMMAND_METADATA, commandType);
        if (!commandMetadata) {
            throw new CommandHandlerNotFoundException(commandType.name);
        }
        return commandMetadata.id;
    }
    registerHandlers(handlers) {
        handlers.forEach((handler) => {
            const target = this.reflectCommandId(handler);
            if (!target) {
                throw new InvalidCommandHandlerException();
            }
            this.bind(handler, target);
        });
    }
    reflectCommandId(handler) {
        const { constructor: handlerType } = Object.getPrototypeOf(handler);
        const command = Reflect.getMetadata(COMMAND_HANDLER_METADATA, handlerType);
        const commandMetadata = Reflect.getMetadata(COMMAND_METADATA, command);
        return commandMetadata.id;
    }
};
CommandBus = __decorate([
    injectable(),
    __metadata("design:paramtypes", [])
], CommandBus);
export { CommandBus };
