"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;
const Path = __importStar(require("node:path"));
const Generator = __importStar(require("@postxl/generator"));
const utils_1 = require("@postxl/utils");
const backend_router_trpc_1 = require("../backend-router-trpc");
const backend_update_1 = require("../backend-update");
const base_1 = require("../base");
const decoders_1 = require("../decoders");
const frontend_core_1 = require("../frontend-core");
const frontend_trpc_client_1 = require("../frontend-trpc-client");
const seed_data_1 = require("../seed-data");
const types_1 = require("../types");
const fields_generator_1 = require("./generators/discriminated-union/fields.generator");
const inputs_generator_1 = require("./generators/discriminated-union/inputs.generator");
const inputs_generator_2 = require("./generators/enum/inputs.generator");
const forms_generator_1 = require("./generators/model/forms.generator");
const inputs_generator_3 = require("./generators/model/inputs.generator");
exports.generatorId = Generator.toGeneratorInterfaceId('frontend-forms');
// TODO Peter: Refactor Generator to so it is simply `ModuleName`
const moduleName = Generator.toBackendModuleName('forms');
exports.generator = {
    id: exports.generatorId,
    requires: [
        base_1.baseGeneratorId,
        types_1.typesGeneratorId,
        decoders_1.decodersGeneratorId,
        frontend_core_1.frontendGeneratorId,
        seed_data_1.seedDataGeneratorId,
        backend_router_trpc_1.backendTrpcRouterGeneratorId,
        backend_update_1.backendUpdateGeneratorId,
        frontend_trpc_client_1.frontendTrpcClientGeneratorId,
    ],
    register: (context) => {
        context.frontend.tsConfigReferences.set(moduleName, {
            name: moduleName,
            filePath: Generator.toFilePath(`components/forms`),
            hasIndex: false,
            isAbsolute: true,
        });
        context.frontend.packageJson.dependencies.push({ packageName: '@tanstack/react-form', version: '1.23.8' });
        const forms = {};
        const models = new Map();
        for (const [modelName, model] of context.models) {
            models.set(modelName, registerModelForms(model));
        }
        const enums = new Map();
        for (const [enumName, enum_] of context.enums) {
            enums.set(enumName, registerEnumForms(enum_));
        }
        return { ...context, forms, models, enums };
    },
    generate: async (context) => {
        const vfs = new Generator.VirtualFileSystem();
        const template = Path.join(__dirname, './template');
        const target = '/frontend';
        const copyToRelativeLocation = (path) => {
            const diskPath = Path.join(template, path);
            const targetPath = Path.join(target, path);
            return { diskPath, targetPath };
        };
        // 1. Copy any static template files into the project. These are files that
        //    should always be generated and do not depend on project or generator
        //    config.
        await context.vfs.loadFolder(copyToRelativeLocation('./'));
        // 2. Generate fields and inputs for any enums
        for (const enum_ of context.enums.values()) {
            const base = `${(0, utils_1.toKebabCase)(enum_.name)}/`;
            vfs.write(Path.join(base, 'input.tsx'), (0, inputs_generator_2.generateEnumInputs)({ enum_ }));
        }
        // 3. Generate create and update forms for each model in the schema.
        for (const model of context.models.values()) {
            const base = `${(0, utils_1.toKebabCase)(model.name)}/`;
            // 3a. Generate inputs for this model. This includes select and search
            //     components
            vfs.write(Path.join(base, 'input.tsx'), (0, inputs_generator_3.generateModelInputs)({ model }));
            // 3b. If this model is editable, generate create and edit forms for it.
            //     These can then be used inside models or elsewhere on the page and
            //     hooked up to trpc routes.
            if (!model.isReadonly) {
                vfs.write(Path.join(base, 'create.tsx'), (0, forms_generator_1.generateModelCreateForm)({ model, context }));
                vfs.write(Path.join(base, 'update.tsx'), (0, forms_generator_1.generateModelUpdateForm)({ model, context }));
            }
            for (const [name, type] of model.types.discriminatedUnions.entries()) {
                const field = model.fields.get(name);
                vfs.write(Path.join((0, utils_1.toKebabCase)(name), 'input.tsx'), (0, inputs_generator_1.generateDiscriminatedUnionInputs)({ type, field }));
                vfs.write(Path.join((0, utils_1.toKebabCase)(name), 'field.tsx'), (0, fields_generator_1.generateDiscriminatedUnionFields)({ context, discriminatedUnion: { type, field } }));
            }
        }
        // 4. Write everything to the context's vfs. All these generated components
        //    end up in the forms folder next to our general ui
        //    components.
        context.vfs.insertFromVfs({ targetPath: `/frontend/src/components/forms`, vfs });
        return Promise.resolve(context); // NOSONAR
    },
};
function registerModelForms(model) {
    const discriminatedUnions = new Map();
    for (const field of model.fields.values()) {
        if (field.kind !== 'discriminatedUnion') {
            continue;
        }
        discriminatedUnions.set(field.name, {
            field: {
                name: Generator.toFunctionName(`${(0, utils_1.toPascalCase)(field.name)}Field`),
                location: Generator.toBackendModuleLocation(`@forms/${(0, utils_1.toKebabCase)(field.name)}/field`),
            },
            schema: {
                name: Generator.toConstantName(`z${(0, utils_1.toPascalCase)(field.name)}Field`),
                location: Generator.toBackendModuleLocation(`@forms/${(0, utils_1.toKebabCase)(field.name)}/field`),
            },
            defaults: {
                name: Generator.toConstantName(`z${(0, utils_1.toPascalCase)(field.name)}DefaultValues`),
                location: Generator.toBackendModuleLocation(`@forms/${(0, utils_1.toKebabCase)(field.name)}/field`),
            },
        });
    }
    const forms = {
        create: {
            name: Generator.toFunctionName(`Create${model._conjugated.PascalCase}`),
            location: Generator.toBackendModuleLocation(`@forms/${model._conjugated.kebabCase}/create`),
        },
        createModal: {
            name: Generator.toFunctionName(`Create${model._conjugated.PascalCase}Modal`),
            location: Generator.toBackendModuleLocation(`@forms/${model._conjugated.kebabCase}/create`),
        },
        update: {
            name: Generator.toFunctionName(`Update${model._conjugated.PascalCase}`),
            location: Generator.toBackendModuleLocation(`@forms/${model._conjugated.kebabCase}/update`),
        },
        updateModal: {
            name: Generator.toFunctionName(`Update${model._conjugated.PascalCase}Modal`),
            location: Generator.toBackendModuleLocation(`@forms/${model._conjugated.kebabCase}/update`),
        },
        inputs: {
            select: {
                name: Generator.toFunctionName(`${model._conjugated.PascalCase}Select`),
                location: Generator.toBackendModuleLocation(`@forms/${model._conjugated.kebabCase}/input`),
            },
            combobox: {
                name: Generator.toFunctionName(`${model._conjugated.PascalCase}Combobox`),
                location: Generator.toBackendModuleLocation(`@forms/${model._conjugated.kebabCase}/input`),
            },
        },
        discriminatedUnions,
    };
    return { ...model, forms };
}
function registerEnumForms(enum_) {
    const location = Generator.toBackendModuleLocation(`@forms/${enum_._conjugated.kebabCase}/input`);
    const inputs = {
        select: { name: Generator.toFunctionName(`${enum_._conjugated.PascalCase}Select`), location },
    };
    return { ...enum_, inputs };
}
//# sourceMappingURL=forms.generator.js.map