"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.generateDataModelDecoder = generateDataModelDecoder;
const Generator = __importStar(require("@postxl/generator"));
/**
 * Checks if a discriminated union has any relation fields (in common fields or any member).
 */
function discriminatedUnionHasRelationFields(field) {
    // Check common fields
    for (const f of field.commonFields.values()) {
        if (f.kind === 'relation') {
            return true;
        }
    }
    // Check member fields
    for (const member of field.members.values()) {
        for (const f of member.fields.values()) {
            if (f.kind === 'relation') {
                return true;
            }
        }
    }
    return false;
}
/**
 * Checks if a model needs lookup maps for Excel encoding.
 * This is true if the model has direct relation fields OR discriminated unions with relation fields.
 */
function modelNeedsLookupMaps(model) {
    for (const field of model.fields.values()) {
        if (field.kind === 'relation') {
            return true;
        }
        if (field.kind === 'discriminatedUnion' && discriminatedUnionHasRelationFields(field)) {
            return true;
        }
    }
    return false;
}
/**
 * Generates the data decoder, aggregating all the models.
 */
function generateDataModelDecoder({ context: { decoders, models } }) {
    const { dataModel, excelDataModel } = decoders;
    const imports = Generator.ImportGenerator.from(dataModel.decoder.zodDecoder.location);
    const encodedTypeEntries = [];
    const decodedTypeEntries = [];
    const encoderEntries = [];
    const decoderEntries = [];
    const encodedExcelTypeEntries = [];
    const encoderExcelEntries = [];
    const decoderExcelEntries = [];
    const transformerExcelEntries = [];
    // Build lookup map type entries for all models (map ID to keyField value)
    const lookupMapTypeEntries = [];
    const lookupMapBuilderEntries = [];
    for (const model of models.values()) {
        imports.addType(model.decoder.flattened.encodedType);
        encodedTypeEntries.push(`${model.decoder.dataModelEntry}: ${model.decoder.flattened.encodedType.name}[] | undefined`);
        imports.addType(model.decoder.excel.encodedType);
        encodedExcelTypeEntries.push(`${model.excelName}: ${model.decoder.excel.encodedType.name}[] | undefined`);
        imports.addType(model.types);
        imports.addType(model.types.id);
        decodedTypeEntries.push(`${model.decoder.dataModelEntry}?: ${model.types.name}[]`);
        imports.add(model.decoder.flattened.encoder);
        encoderEntries.push(`${model.decoder.dataModelEntry}: input.${model.decoder.dataModelEntry}?.map(${model.decoder.flattened.encoder.name}) ?? undefined`);
        imports.add(model.decoder.excel.encoder);
        // Build lookup map type entry (maps ID to keyField value for this model)
        lookupMapTypeEntries.push(`${model.decoder.dataModelEntry}: Map<${model.types.id.name}, string>`);
        // Build lookup map builder entry
        const keyFieldName = model.keyField.name;
        lookupMapBuilderEntries.push(`${model.decoder.dataModelEntry}: new Map((input.${model.decoder.dataModelEntry} ?? []).map(item => [item.id, String(item.${keyFieldName})]))`);
        imports.add(model.decoder.flattened.decoder.zodDecoder);
        decoderEntries.push(`${model.decoder.dataModelEntry}: z.array(${model.decoder.flattened.decoder.zodDecoder.name}).optional()`);
        imports.add(model.decoder.excel.decoder.zodDecoder);
        decoderExcelEntries.push(`${model.excelName}: z.array(${model.decoder.excel.decoder.zodDecoder.name}).optional()`);
        transformerExcelEntries.push(`${model.decoder.dataModelEntry}: v.${model.excelName} ?? []`);
    }
    // Generate encoder entries for Excel - models with relations (direct or via DU) need lookup maps
    for (const model of models.values()) {
        if (modelNeedsLookupMaps(model)) {
            encoderExcelEntries.push(`${model.excelName}: input.${model.decoder.dataModelEntry}?.map(item => ${model.decoder.excel.encoder.name}(item, lookupMaps)) ?? undefined`);
        }
        else {
            encoderExcelEntries.push(`${model.excelName}: input.${model.decoder.dataModelEntry}?.map(${model.decoder.excel.encoder.name}) ?? undefined`);
        }
    }
    return `
import * as z from 'zod'
${imports.generate()}

/**
 * All data from the data model exported as a flattened object
 */
export type ${dataModel.encodedType.name} = {
  ${encodedTypeEntries.join(',\n')}
}

/**
 * All data after decoding an imported flattened object
 */
export type ${dataModel.decodedType.name} = {
  ${decodedTypeEntries.join(',\n')}
}

/**
 * Lookup maps for resolving IDs to keyField values during Excel export.
 * Each map contains ID -> keyField value mappings for a specific model.
 * This is used to export human-readable keys instead of UUIDs in relation fields.
 */
export type IdToKeyLookupMaps = {
  ${lookupMapTypeEntries.join(',\n')}
}

/**
 * Builds lookup maps from the DataModel for ID-to-key resolution during export.
 * These maps allow the Excel encoder to output keyField values instead of IDs for relation fields.
 */
function buildIdToKeyLookupMaps(input: ${dataModel.decodedType.name}): IdToKeyLookupMaps {
  return {
    ${lookupMapBuilderEntries.join(',\n')}
  }
}

export function ${dataModel.encoder.name}(input: ${dataModel.decodedType.name}): ${dataModel.encodedType.name} {
  return {
    ${encoderEntries.join(',\n')}
  }
}

/**
 * Decoder that converts flattened model data to model data
 */
export const ${dataModel.decoder.zodDecoder.name} = z
  .object({
    ${decoderEntries.join(',\n')}
  })

export function ${dataModel.decoder.parseFunction.name}(input: ${dataModel.encodedType.name}): ${dataModel.decodedType.name} {
  return ${dataModel.decoder.zodDecoder.name}.parse(input)
}

/**
 * All data from the data model exported as a flattened Excel object
 */
export type ${excelDataModel.encodedType.name} = {
  ${encodedExcelTypeEntries.join(',\n')}
}

/**
 * Encodes a DataModel to Excel format, converting relation IDs to human-readable keys.
 * This allows exported Excel files to contain the same format as imported Excel files,
 * making round-trip import/export consistent.
 */
export function ${excelDataModel.encoder.name}(input: ${dataModel.decodedType.name}): ${excelDataModel.encodedType.name} {
  // Build lookup maps for ID-to-key resolution
  const lookupMaps = buildIdToKeyLookupMaps(input)

  return {
    ${encoderExcelEntries.join(',\n')}
  }
}

/**
 * Decoder that converts flattened Excel model data to model data
 */
export const ${excelDataModel.decoder.zodDecoder.name} = z
  .object({
    ${decoderExcelEntries.join(',\n')}
  })
  .transform((v) => ({
    ${transformerExcelEntries.join(',\n')}
  }))

export function ${excelDataModel.decoder.parseFunction.name}(input: ${excelDataModel.encodedType.name}): ${dataModel.decodedType.name} {
  return ${excelDataModel.decoder.zodDecoder.name}.parse(input)
}
`;
}
//# sourceMappingURL=datamodel-decoder.generator.js.map