"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProviderInvokeCommand = void 0;
const tslib_1 = require("tslib");
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const app_1 = require("@deepkit/app");
const injector_1 = require("@deepkit/injector");
const orm_1 = require("@deepkit/orm");
const type_1 = require("@deepkit/type");
const resolver_1 = require("../../app/resolver");
const injection_1 = require("../../helpers/framework/injection");
let ProviderInvokeCommand = class ProviderInvokeCommand {
    constructor() { }
    async execute(providerName, methodName, argsJson) {
        const providers = (0, injection_1.getProviderTree)((0, resolver_1.getAppModule)());
        const provider = providers.find(__assignType(p => p.name === providerName, ['p', '', 'P"2!"/"']));
        if (!provider) {
            throw new injector_1.InjectorError(`Provider ${providerName} not found.`);
        }
        const resolved = (0, resolver_1.getOrCreateInjectorForModule)(provider.module).get(provider.provide);
        const resolvedType = type_1.ReflectionClass.from(resolved);
        if (!resolvedType.hasMethod(methodName)) {
            throw new injector_1.InjectorError(`Provider ${providerName} does not have method ${methodName}.`);
        }
        const args = argsJson ? JSON.parse(argsJson) : [];
        // DK lazily starts the database registry, but we don't have any calls that
        // would cause that. without the registry, the application shutdown hook to
        // disconect from the database is never executed. thus, we'll invoke this manually.
        (0, resolver_1.r)(orm_1.DatabaseRegistry).init();
        // eslint-disable-next-line prefer-spread, @typescript-eslint/no-explicit-any
        return resolved[methodName].apply(resolved, args);
    }
};
exports.ProviderInvokeCommand = ProviderInvokeCommand;
ProviderInvokeCommand.__type = ['constructor', 'providerName', 'methodName', 'argsJson', 'execute', 'ProviderInvokeCommand', 'P"0!P&2"&2#&2$8"0%5w&'];
exports.ProviderInvokeCommand = ProviderInvokeCommand = tslib_1.__decorate([
    app_1.cli.controller('provider:invoke', {
        description: 'Invoke a function in any registered provider'
    }),
    tslib_1.__metadata("design:paramtypes", [])
], ProviderInvokeCommand);
//# sourceMappingURL=invoke.js.map