"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generator = exports.generatorId = void 0;
exports.isUpdateModelResult_Exists = isUpdateModelResult_Exists;
const Generator = __importStar(require("@postxl/generator"));
const utils_1 = require("@postxl/utils");
const Actions = __importStar(require("../backend-actions"));
const backend_core_1 = require("../backend-core");
const backend_repositories_1 = require("../backend-repositories");
const backend_view_1 = require("../backend-view");
const base_1 = require("../base");
const types_1 = require("../types");
const bulk_service_generator_1 = require("./bulk-service.generator");
const model_update_service_generator_1 = require("./model-update-service.generator");
const update_actions_decoders_1 = require("./update-actions.decoders");
const update_module_generator_1 = require("./update-module.generator");
const update_service_generator_1 = require("./update-service.generator");
function isUpdateModelResult_Exists(model) {
    return model.update.kind === 'exists';
}
exports.generatorId = Generator.toGeneratorInterfaceId('backend-update');
exports.generator = {
    id: exports.generatorId,
    requires: [
        backend_core_1.backendGeneratorId,
        base_1.baseGeneratorId,
        types_1.typesGeneratorId,
        Actions.backendActionsGeneratorId,
        backend_repositories_1.backendRepositoriesGeneratorId,
        backend_view_1.backendViewGeneratorId,
    ],
    register: (context) => {
        const module = {
            name: Generator.toClassName('UpdateModule'),
            location: Generator.toBackendModuleLocation(`@update/update.module`),
        };
        const updateModule = {
            name: Generator.toBackendModuleName('update'),
            moduleClass: module,
        };
        context.backend.modules.push(updateModule);
        const scopes = new Set();
        const models = new Map();
        for (const [modelName, model] of context.models) {
            const modelWithUpdates = registerModelUpdate(model);
            models.set(modelName, modelWithUpdates);
            if (modelWithUpdates.update.kind !== 'skipped') {
                scopes.add(modelWithUpdates.update.action.scope);
            }
        }
        const serviceLocation = Generator.toBackendModuleLocation(`@update/update.service`);
        const bulkServiceLocation = Generator.toBackendModuleLocation(`@update/bulk.service`);
        const actionProvider = {
            module: updateModule,
            service: {
                name: Generator.toClassName('UpdateService'),
                variableName: Generator.toVariableName('updateService'),
                location: serviceLocation,
            },
            scopes,
            actions: {
                summary: {
                    action: {
                        name: Generator.toTypeName('Action_Update'),
                        location: serviceLocation,
                    },
                    result: {
                        name: Generator.toTypeName('ActionResult_Update'),
                        location: serviceLocation,
                    },
                },
            },
            bulk: {
                service: {
                    name: Generator.toClassName('BulkService'),
                    location: bulkServiceLocation,
                    executeSingleStepMethodName: Generator.toFunctionName('executeBulkMutation'),
                    executeMultipleStepsMethodName: Generator.toFunctionName('executeBulkMutations'),
                },
                type: {
                    name: Generator.toTypeName('BulkMutation'),
                    location: bulkServiceLocation,
                },
                modelType: {
                    name: Generator.toTypeName('BulkMutationForModel'),
                    location: bulkServiceLocation,
                },
            },
        };
        context.actions.providers.push(actionProvider);
        return {
            ...context,
            update: actionProvider,
            models,
        };
    },
    generate: (context) => {
        const vfsSrc = new Generator.VirtualFileSystem();
        for (const model of context.models.values()) {
            if (isUpdateModelResult_Exists(model)) {
                vfsSrc.write(Generator.toLocalFile(model.update.service), (0, model_update_service_generator_1.generateModelUpdateService)({ model, context }));
            }
        }
        vfsSrc.write(Generator.toLocalFile(context.update.service), (0, update_service_generator_1.generateUpdateService)(context));
        vfsSrc.write(Generator.toLocalFile(context.update.bulk.service), (0, bulk_service_generator_1.generateBulkService)(context));
        vfsSrc.write(Generator.toLocalFile(context.update.module.moduleClass), (0, update_module_generator_1.generateUpdateModule)(context)); // NOSONAR
        const vfs = new Generator.VirtualFileSystem();
        vfs.insertFromVfs({ targetPath: 'src', vfs: vfsSrc });
        vfs.write('/tsconfig.lib.json', Generator.generateTsConfig('update'));
        context.vfs.insertFromVfs({ targetPath: 'backend/libs/update', vfs });
        return Promise.resolve(context);
    },
};
function registerModelUpdate(model) {
    if (model.repository.kind === 'NoRepository' || model.isReadonly) {
        return { ...model, update: { kind: 'skipped' } };
    }
    const location = Generator.toBackendModuleLocation(`@update/${model._conjugated.camelCase}.update.service`);
    const { standardActions, actions } = getUpdateActions(model, location);
    const update = {
        kind: 'exists',
        service: {
            name: Generator.toClassName(`${model._conjugated.PascalCase}UpdateService`),
            location,
            variableName: Generator.toVariableName(`${model._conjugated.camelCasePlural}`),
        },
        action: {
            type: {
                name: Generator.toTypeName(`Action_${model._conjugated.PascalCase}`),
                location,
            },
            resultTypeMap: {
                name: Generator.toTypeName(`ActionResult_${model._conjugated.PascalCase}`),
                location,
            },
            scope: Actions.toScopeName(model._conjugated.camelCase),
            standardActions,
            actions,
        },
        bulkMutationFieldName: Generator.toVariableName(model._conjugated.camelCasePlural),
    };
    return { ...model, update };
}
function getUpdateActions(model, location) {
    if (!model.source) {
        throw new Error(`Model ${model.name} does not have a source`);
    }
    const result = [];
    const actions = update_actions_decoders_1.zUpdateActions.parse(model.source);
    for (const [name, description] of Object.entries(actions.actions)) {
        const updateAction = {
            kind: 'custom',
            name,
            ...getUpdateAction_Shared({ name, description, resultType: undefined, location, model }),
        };
        result.push(updateAction);
    }
    const standardActions = {
        create: undefined,
        createMany: undefined,
        update: undefined,
        updateMany: undefined,
        updateField: undefined,
        upsert: undefined,
        upsertMany: undefined,
        delete: undefined,
        deleteMany: undefined,
        clone: undefined,
        cloneMany: undefined,
    };
    for (const name of actions.standardActions) {
        const { description, resultType } = getAction_StandardParameters(name, model);
        const action = {
            kind: 'standard',
            name,
            ...getUpdateAction_Shared({ name, description, resultType, location, model }),
        };
        standardActions[name] = action;
        result.push(action);
    }
    return { actions: result, standardActions };
}
function getUpdateAction_Shared({ name, description, resultType, location, model, }) {
    const pascalCase = (0, utils_1.toPascalCase)(name);
    return {
        type: {
            name: Generator.toTypeName(`Action_${model._conjugated.PascalCase}_${pascalCase}`),
            location,
        },
        description,
        payload: {
            type: {
                name: Generator.toTypeName(`${pascalCase}Payload`),
                location,
            },
            decoder: {
                name: Generator.toFunctionName(`z${pascalCase}Decoder`),
                location,
            },
        },
        result: {
            name: Generator.toTypeName(`${pascalCase}Result`),
            location,
            definition: resultType,
        },
    };
}
function getAction_StandardParameters(action, model) {
    switch (action) {
        case 'create':
            return {
                resultType: model.types.name,
                description: `Create a new ${model.userFriendlyName}`,
            };
        case 'createMany':
            return {
                resultType: `${model.types.name}[]`,
                description: `Create multiple new ${model.userFriendlyNamePlural}`,
            };
        case 'update':
            return {
                resultType: model.types.name,
                description: `Update an existing ${model.userFriendlyName}`,
            };
        case 'updateMany':
            return {
                resultType: `${model.types.name}[]`,
                description: `Update multiple existing ${model.userFriendlyNamePlural}`,
            };
        case 'updateField':
            return {
                resultType: model.types.name,
                description: `Update a single field of an existing ${model.userFriendlyName}`,
            };
        case 'upsert':
            return {
                resultType: model.types.name,
                description: `Create or update a ${model.userFriendlyName}`,
            };
        case 'upsertMany':
            return {
                resultType: `${model.types.name}[]`,
                description: `Create or update multiple ${model.userFriendlyNamePlural}`,
            };
        case 'delete':
            return {
                resultType: model.types.id.name,
                description: `Delete an existing ${model.userFriendlyName}`,
            };
        case 'deleteMany':
            return {
                resultType: `${model.types.id.name}[]`,
                description: `Delete multiple existing ${model.userFriendlyNamePlural}`,
            };
        case 'clone':
            return {
                resultType: model.types.name,
                description: `Clone an existing ${model.userFriendlyName}`,
            };
        case 'cloneMany':
            return {
                resultType: `${model.types.name}[]`,
                description: `Clone multiple existing ${model.userFriendlyNamePlural}`,
            };
        default:
            throw new utils_1.ExhaustiveSwitchCheck(action);
    }
}
//# sourceMappingURL=update.generator.js.map