"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 Generator = __importStar(require("@postxl/generator"));
const utils_1 = require("@postxl/utils");
const backend_core_1 = require("../backend-core");
const base_1 = require("../base");
const types_1 = require("../types");
const datamodel_decoder_generator_1 = require("./datamodel-decoder.generator");
const discriminated_union_decoder_generator_1 = require("./discriminated-union.decoder.generator");
const enum_decoder_generator_1 = require("./enum-decoder.generator");
const model_decoder_generator_1 = require("./model-decoder.generator");
exports.generatorId = Generator.toGeneratorInterfaceId('data-decoder');
const moduleName = Generator.toBackendModuleName('decoders');
exports.generator = {
    id: exports.generatorId,
    requires: [backend_core_1.backendGeneratorId, base_1.baseGeneratorId, types_1.typesGeneratorId],
    register: (context) => {
        const decodersModule = {
            name: moduleName,
        };
        context.backend.modules.push(decodersModule);
        const dataModelLocation = Generator.toBackendModuleLocation(`@${moduleName}/data-model.decoder`);
        const dataModel = {
            decoder: {
                hasTransformer: false,
                zodDecoder: {
                    name: Generator.toConstantName(`zDataModelDecoder`),
                    location: dataModelLocation,
                },
                parseFunction: {
                    name: Generator.toFunctionName(`decodeDataModel`),
                    location: dataModelLocation,
                },
            },
            encodedType: {
                name: Generator.toTypeName(`DataModelFlattened`),
                location: dataModelLocation,
            },
            decodedType: {
                name: Generator.toTypeName(`DataModel`),
                location: dataModelLocation,
            },
            encoder: {
                name: Generator.toFunctionName(`flattenDataModel`),
                location: dataModelLocation,
            },
        };
        const excelDataModel = {
            decoder: {
                hasTransformer: false,
                zodDecoder: {
                    name: Generator.toConstantName(`zExcelDataModelDecoder`),
                    location: dataModelLocation,
                },
                parseFunction: {
                    name: Generator.toFunctionName(`decodeExcelDataModel`),
                    location: dataModelLocation,
                },
            },
            encodedType: {
                name: Generator.toTypeName(`ExcelDataModelFlattened`),
                location: dataModelLocation,
            },
            decodedType: {
                name: Generator.toTypeName(`DataModel`),
                location: dataModelLocation,
            },
            encoder: {
                name: Generator.toFunctionName(`flattenExcelDataModel`),
                location: dataModelLocation,
            },
        };
        const decoders = {
            location: Generator.toBackendModuleLocation(`@${moduleName}`),
            dataModel,
            excelDataModel,
        };
        const models = new Map();
        for (const [modelName, model] of context.models) {
            const modelWithDecoder = registerModelDecoder(model);
            models.set(modelName, modelWithDecoder);
        }
        const enums = new Map();
        for (const [enumName, enum_] of context.enums) {
            const enumWithDecoder = registerEnumDecoder(enum_);
            enums.set(enumName, enumWithDecoder);
        }
        return { ...context, decoders, models, enums };
    },
    generate: async (context) => {
        const indexLocation = Generator.toBackendModuleLocation(`@decoders/index`);
        const index = new Generator.IndexGenerator(indexLocation);
        const vfsSrc = new Generator.VirtualFileSystem();
        for (const model of context.models.values()) {
            vfsSrc.write(Generator.toLocalFile(model.decoder.decoder.zodDecoder), (0, model_decoder_generator_1.generateModelDecoder)({ model, context }));
            index.add(model.decoder.decoder.zodDecoder);
            for (const du of model.decoder.discriminatedUnions.values()) {
                vfsSrc.write(Generator.toLocalFile(du.decoder.zodDecoder), (0, discriminated_union_decoder_generator_1.generateDiscriminatedUnionDecoder)({ model, discriminatedUnion: du, context }));
                index.add(du.decoder.zodDecoder);
            }
        }
        for (const enum_ of context.enums.values()) {
            vfsSrc.write(Generator.toLocalFile(enum_.decoder.decoder.zodDecoder), (0, enum_decoder_generator_1.generateEnumDecoder)({ enum_, context }));
            index.add(enum_.decoder.decoder.zodDecoder);
        }
        vfsSrc.write(Generator.toLocalFile(context.decoders.dataModel.decoder.zodDecoder), (0, datamodel_decoder_generator_1.generateDataModelDecoder)({ context }));
        index.add(context.decoders.dataModel.decoder.zodDecoder);
        vfsSrc.write(Generator.toLocalFile({ location: indexLocation }), index.generate());
        const vfs = new Generator.VirtualFileSystem();
        vfs.insertFromVfs({ targetPath: 'src', vfs: vfsSrc });
        vfs.write('/tsconfig.lib.json', Generator.generateTsConfig('decoders'));
        context.vfs.insertFromVfs({ targetPath: 'backend/libs/decoders', vfs });
        return Promise.resolve(context); // NOSONAR
    },
};
function registerModelDecoder(model) {
    const location = Generator.toBackendModuleLocation(`@${moduleName}/${model._conjugated.camelCase}.model.decoder`);
    const discriminatedUnions = registerDiscriminatedUnionDecoders(model);
    const decoder = {
        discriminatedUnions,
        dataModelEntry: model._conjugated.camelCasePlural,
        decoder: {
            hasTransformer: true,
            zodDecoder: {
                name: Generator.toConstantName(`z${model._conjugated.PascalCase}Decoder`),
                location,
            },
            rawInputValidation: {
                name: Generator.toConstantName(`zRaw${model._conjugated.PascalCase}Decoder`),
                location,
            },
            rawInputType: {
                name: Generator.toTypeName(`Raw${model._conjugated.PascalCase}`),
                location,
            },
            transformer: {
                name: Generator.toFunctionName(`flattenedRawTo${model._conjugated.PascalCase}Transformer`),
                location,
            },
            parseFunction: {
                name: Generator.toFunctionName(`decode${model._conjugated.PascalCase}`),
                location,
            },
        },
        flattened: {
            encodedType: {
                name: Generator.toTypeName(`Raw${model._conjugated.PascalCase}Flattened`),
                location,
            },
            decodedType: {
                name: Generator.toTypeName(`${model._conjugated.PascalCase}`),
                location,
            },
            decoder: {
                hasTransformer: true,
                zodDecoder: {
                    name: Generator.toConstantName(`z${model._conjugated.PascalCase}FlattenedDecoder`),
                    location,
                },
                rawInputValidation: {
                    name: Generator.toConstantName(`zRaw${model._conjugated.PascalCase}FlattenedDecoder`),
                    location,
                },
                rawInputType: {
                    name: Generator.toTypeName(`Raw${model._conjugated.PascalCase}Flattened`),
                    location,
                },
                transformer: {
                    name: Generator.toFunctionName(`flattenedRawTo${model._conjugated.PascalCase}Transformer`),
                    location,
                },
                parseFunction: {
                    name: Generator.toFunctionName(`decodeFlattened${model._conjugated.PascalCase}`),
                    location,
                },
            },
            encoder: {
                name: Generator.toFunctionName(`encode${model._conjugated.PascalCase}AsFlattened`),
                location,
            },
        },
        excel: {
            encodedType: {
                name: Generator.toTypeName(`Raw${model._conjugated.PascalCase}ExcelFlattened`),
                location,
            },
            decodedType: {
                name: Generator.toTypeName(`${model._conjugated.PascalCase}`),
                location,
            },
            decoder: {
                hasTransformer: true,
                zodDecoder: {
                    name: Generator.toConstantName(`z${model._conjugated.PascalCase}ExcelFlattenedDecoder`),
                    location,
                },
                rawInputValidation: {
                    name: Generator.toConstantName(`zRaw${model._conjugated.PascalCase}ExcelFlattenedDecoder`),
                    location,
                },
                rawInputType: {
                    name: Generator.toTypeName(`Raw${model._conjugated.PascalCase}ExcelFlattened`),
                    location,
                },
                transformer: {
                    name: Generator.toFunctionName(`excelFlattenedRawTo${model._conjugated.PascalCase}Transformer`),
                    location,
                },
                parseFunction: {
                    name: Generator.toFunctionName(`decodeExcelFlattened${model._conjugated.PascalCase}`),
                    location,
                },
            },
            encoder: {
                name: Generator.toFunctionName(`encode${model._conjugated.PascalCase}AsExcelFlattened`),
                location,
            },
        },
    };
    verifyExcelNames(model);
    return { ...model, decoder };
}
function registerDiscriminatedUnionDecoders(model) {
    const result = new Map();
    for (const field of model.fields.values()) {
        if (field.kind !== 'discriminatedUnion') {
            continue;
        }
        const pascalCase = (0, utils_1.toPascalCase)(field.name);
        const location = Generator.toBackendModuleLocation(`@${moduleName}/${field.name}.discriminatedUnion.decoder`);
        const decoder = {
            field,
            decoder: {
                hasTransformer: false,
                zodDecoder: {
                    name: Generator.toConstantName(`z${pascalCase}Decoder`),
                    location,
                },
                parseFunction: {
                    name: Generator.toFunctionName(`decode${pascalCase}`),
                    location,
                },
            },
            flattened: {
                encodedType: {
                    name: Generator.toTypeName(`Raw${pascalCase}Flattened`),
                    location,
                },
                decodedType: {
                    name: Generator.toTypeName(`${pascalCase}`),
                    location,
                },
                decoder: {
                    hasTransformer: true,
                    zodDecoder: {
                        name: Generator.toConstantName(`z${pascalCase}FlattenedDecoder`),
                        location,
                    },
                    rawInputValidation: {
                        name: Generator.toConstantName(`zRaw${pascalCase}FlattenedDecoder`),
                        location,
                    },
                    rawInputType: {
                        name: Generator.toTypeName(`Raw${pascalCase}Flattened`),
                        location,
                    },
                    transformer: {
                        name: Generator.toFunctionName(`flattenedRawTo${pascalCase}Transformer`),
                        location,
                    },
                    parseFunction: {
                        name: Generator.toFunctionName(`decodeFlattened${pascalCase}`),
                        location,
                    },
                },
                encoder: {
                    name: Generator.toFunctionName(`encode${pascalCase}AsFlattened`),
                    location,
                },
            },
            excel: {
                encodedType: {
                    name: Generator.toTypeName(`Raw${pascalCase}ExcelFlattened`),
                    location,
                },
                decodedType: {
                    name: Generator.toTypeName(`${pascalCase}`),
                    location,
                },
                decoder: {
                    hasTransformer: true,
                    zodDecoder: {
                        name: Generator.toConstantName(`z${pascalCase}ExcelFlattenedDecoder`),
                        location,
                    },
                    rawInputValidation: {
                        name: Generator.toConstantName(`zRaw${pascalCase}ExcelFlattenedDecoder`),
                        location,
                    },
                    rawInputType: {
                        name: Generator.toTypeName(`Raw${pascalCase}ExcelFlattened`),
                        location,
                    },
                    transformer: {
                        name: Generator.toFunctionName(`excelFlattenedRawTo${pascalCase}Transformer`),
                        location,
                    },
                    parseFunction: {
                        name: Generator.toFunctionName(`decodeExcelFlattened${pascalCase}`),
                        location,
                    },
                },
                encoder: {
                    name: Generator.toFunctionName(`encode${pascalCase}AsExcelFlattened`),
                    location,
                },
            },
        };
        result.set(field.name, decoder);
    }
    return result;
}
function registerEnumDecoder(enum_) {
    const location = Generator.toBackendModuleLocation(`@${moduleName}/${enum_._conjugated.camelCase}.enum.decoder`);
    const decoder = {
        decoder: {
            hasTransformer: true,
            zodDecoder: {
                name: Generator.toConstantName(`z${enum_._conjugated.PascalCase}Decoder`),
                location,
            },
            rawInputValidation: {
                name: Generator.toConstantName(`zRaw${enum_._conjugated.PascalCase}Decoder`),
                location,
            },
            rawInputType: {
                name: Generator.toTypeName(`Raw${enum_._conjugated.PascalCase}`),
                location,
            },
            transformer: {
                name: Generator.toFunctionName(`raw${enum_._conjugated.PascalCase}ToFlattened`),
                location,
            },
            parseFunction: {
                name: Generator.toFunctionName(`decode${enum_._conjugated.PascalCase}`),
                location,
            },
        },
        encoder: {
            name: Generator.toFunctionName(`encode${enum_._conjugated.PascalCase}`),
            location,
        },
    };
    return { ...enum_, decoder };
}
/**
 * Verifies that all field excel names in the given model are unique.
 *
 * This function ensures that field excel names do not conflict, as duplicate names
 * can cause issues during the Excel import/export process. Excel relies on unique
 * names to map data correctly, and duplicates may lead to data corruption
 * or incorrect mappings.
 *
 * If duplicate labels are found, an error is thrown with details about the
 * conflicting fields.
 *
 * @param model - The model whose field labels are to be verified.
 * @throws {Error} If duplicate field labels are detected.
 */
function verifyExcelNames(model) {
    const names = new Map();
    for (const field of model.fields.values()) {
        if (names.has(field.excelName)) {
            const existing = names.get(field.excelName);
            existing.push((0, utils_1.red)(`${model.name}.${field.excelName}`));
            continue;
        }
        names.set(field.excelName, [(0, utils_1.red)(`${model.name}.${field.name}`)]);
    }
    const errors = [];
    for (const [excelName, fields] of names.entries()) {
        if (fields.length > 1) {
            errors.push(`Duplicate name "${(0, utils_1.yellow)(excelName)}" for fields ${fields.join(', ')}! Field names must be unique to allow Excel import/export!"`);
        }
    }
    if (errors.length > 0) {
        throw new Error(errors.join('\n'));
    }
}
//# sourceMappingURL=decoders.generator.js.map