import { Container, injectable } from "inversify";
import type { interfaces } from "inversify";
import { IRequest, IRequestClass } from "..";
import { PrimariaApi } from "../api/api";

//TODO aixo ho fan ja les Broker extensions de plugins/core. Veure si s'ha de canviar
export const registerRequest =
  (api: PrimariaApi, container: Container) =>
  (command: IRequestClass<any>, handler: interfaces.Newable<any>) => {
    container.bind(handler).to(handler).inTransientScope();
    injectable()(handler);
    const disposable = api.broker.registerRequest(command, (cmd: IRequest<any>) => {
      const handlerInstance = container.get(handler);
      return handlerInstance.handle(cmd);
    });
    return {
      dispose: () => {
        container.isBound(handler) && container.unbind(handler);
        disposable.dispose();
      },
    };
  };
