"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generator = exports.generatorId = exports.toScopeName = void 0;
const node_path_1 = require("node:path");
const zod_1 = __importDefault(require("zod"));
const Generator = __importStar(require("@postxl/generator"));
const Schema = __importStar(require("@postxl/schema"));
const backend_core_1 = require("../backend-core");
const backend_database_prisma_1 = require("../backend-database-prisma");
const base_1 = require("../base");
const types_1 = require("../types");
const action_types_generator_1 = require("./generators/action-types.generator");
const actions_config_class_generator_1 = require("./generators/actions-config-class.generator");
const actions_module_generator_1 = require("./generators/actions-module.generator");
const authorization_service_generator_1 = require("./generators/authorization-service.generator");
const dispatcher_service_generator_1 = require("./generators/dispatcher-service.generator");
const execution_class_generator_1 = require("./generators/execution-class.generator");
const execution_interface_generator_1 = require("./generators/execution-interface.generator");
const zScopeName = zod_1.default.string().brand('PXL.ScopeName');
const toScopeName = (input) => zScopeName.parse(input);
exports.toScopeName = toScopeName;
exports.generatorId = Generator.toGeneratorInterfaceId('backend-actions');
exports.generator = {
    id: exports.generatorId,
    requires: [backend_core_1.backendGeneratorId, base_1.baseGeneratorId, types_1.typesGeneratorId, backend_database_prisma_1.databaseGeneratorId],
    register: (context) => {
        verifyContext(context);
        const module = {
            name: Generator.toClassName('ActionsModule'),
            location: Generator.toBackendModuleLocation(`@actions/actions.module`),
        };
        const configLocation = Generator.toBackendModuleLocation(`@actions/actions-config.class`);
        const config = {
            name: Generator.toClassName('ActionsConfig'),
            location: configLocation,
            options: {
                name: Generator.toTypeName('ActionsModuleOptions'),
                location: configLocation,
            },
        };
        const actionsModule = {
            name: Generator.toBackendModuleName('actions'),
            moduleClass: module,
            apiModuleRegistration: {
                code: Generator.ts('ActionsModule.forRoot(config.actions)'),
            },
            envConfig: {
                transformer: Generator.ts('actions: { useInMemory: !val.STATEFUL }'),
                //Stateful is already defined as an app wide setting by the backend core generator
                dotEnvExample: ``,
                decoder: Generator.ts(``),
            },
        };
        context.backend.modules.push(actionsModule);
        const actions = {
            module,
            config,
            dispatcher: {
                name: Generator.toClassName('DispatcherService'),
                location: Generator.toBackendModuleLocation(`@actions/dispatcher.service`),
            },
            authorization: {
                service: {
                    name: Generator.toClassName('AuthorizationService'),
                    location: Generator.toBackendModuleLocation(`@actions/authorization/authorization.service`),
                },
            },
            execution: {
                interface: {
                    name: Generator.toTypeName('IActionExecution'),
                    location: Generator.toBackendModuleLocation(`@actions/execution/execution.interface`),
                    actionOperationId: {
                        name: Generator.toTypeName('ActionOperationId'),
                        location: Generator.toBackendModuleLocation(`@actions/execution/execution.interface`),
                    },
                    toBrandedActionOperationId: {
                        name: Generator.toFunctionName('toActionOperationId'),
                        location: Generator.toBackendModuleLocation(`@actions/execution/execution.interface`),
                    },
                },
                class: {
                    name: Generator.toClassName('ActionExecutionFactory'),
                    location: Generator.toBackendModuleLocation(`@actions/execution/execution.class`),
                },
                _internalName: Generator.toClassName('ActionExecution'),
                mutations: {
                    create: {
                        start: Generator.toFunctionName('startCreateMutation'),
                        finish: Generator.toFunctionName('finishCreateMutation'),
                    },
                    createMany: {
                        start: Generator.toFunctionName('startCreateManyMutation'),
                        finish: Generator.toFunctionName('finishCreateManyMutation'),
                    },
                    update: {
                        start: Generator.toFunctionName('startUpdateMutation'),
                        finish: Generator.toFunctionName('finishUpdateMutation'),
                    },
                    updateMany: {
                        start: Generator.toFunctionName('startUpdateManyMutation'),
                        finish: Generator.toFunctionName('finishUpdateManyMutation'),
                    },
                    delete: {
                        start: Generator.toFunctionName('startDeleteMutation'),
                        finish: Generator.toFunctionName('finishDeleteMutation'),
                    },
                    deleteMany: {
                        start: Generator.toFunctionName('startDeleteManyMutation'),
                        finish: Generator.toFunctionName('finishDeleteManyMutation'),
                    },
                    clone: {
                        start: Generator.toFunctionName('startCloneMutation'),
                        finish: Generator.toFunctionName('finishCloneMutation'),
                    },
                },
                transformation: {
                    executeMultiple: Generator.toFunctionName('executeTransformations'),
                    executeSingle: Generator.toFunctionName('executeTransformation'),
                    start: Generator.toFunctionName('startTransformation'),
                    finish: Generator.toFunctionName('finishTransformation'),
                },
                errorOperation: Generator.toFunctionName('errorActionOperation'),
            },
            providers: [],
            summary: {
                action: {
                    name: Generator.toTypeName('Action'),
                    location: Generator.toBackendModuleLocation(`@actions/actions.types`),
                },
                result: {
                    name: Generator.toTypeName('ActionResult'),
                    location: Generator.toBackendModuleLocation(`@actions/actions.types`),
                },
                resultOfActionHelper: {
                    name: Generator.toTypeName('ResultOfAction'),
                    location: Generator.toBackendModuleLocation(`@actions/actions.types`),
                },
            },
        };
        return { ...context, actions };
    },
    generate: async (context) => {
        const { actions } = context;
        const srcVfs = new Generator.VirtualFileSystem();
        srcVfs.write(Generator.toLocalFile(actions.dispatcher), (0, dispatcher_service_generator_1.generateDispatcher)(context));
        srcVfs.write(Generator.toLocalFile(actions.authorization.service), (0, authorization_service_generator_1.generateAuthorizationService)(context));
        srcVfs.write(Generator.toLocalFile(actions.execution.class), (0, execution_class_generator_1.generateActionExecutionClass)(context));
        srcVfs.write(Generator.toLocalFile(actions.execution.interface), (0, execution_interface_generator_1.generateActionExecutionInterface)(context));
        srcVfs.write(Generator.toLocalFile(actions.summary.action), (0, action_types_generator_1.generateActionTypes)(actions));
        srcVfs.write(Generator.toLocalFile(actions.config), (0, actions_config_class_generator_1.generateActionsConfig)(context));
        srcVfs.write(Generator.toLocalFile(actions.module), (0, actions_module_generator_1.generateActionsModule)(context));
        const vfs = new Generator.VirtualFileSystem();
        vfs.insertFromVfs({ targetPath: 'src', vfs: srcVfs });
        vfs.write('/tsconfig.lib.json', Generator.generateTsConfig('types'));
        await vfs.loadFolder({ diskPath: (0, node_path_1.resolve)(__dirname, './template') });
        context.vfs.insertFromVfs({ targetPath: 'backend/libs/actions', vfs: vfs });
        return context;
    },
};
function verifyContext(context) {
    Generator.verifyModelExists(Schema.defaultModelNames.action, context);
    Generator.verifyModelExists(Schema.defaultModelNames.mutation, context);
    Generator.verifyModelExists(Schema.defaultModelNames.user, context);
    Generator.verifyEnumExists(Schema.defaultEnumNames.actionStatus, context);
    Generator.verifyEnumExists(Schema.defaultEnumNames.mutationStatus, context);
    Generator.verifyEnumExists(Schema.defaultEnumNames.mutationKind, context);
}
//# sourceMappingURL=actions.generator.js.map