"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.generateModelStub = generateModelStub;
exports.generateDiscriminatedUnionStub = generateDiscriminatedUnionStub;
const Generator = __importStar(require("@postxl/generator"));
const utils_1 = require("@postxl/utils");
function generateModelStub({ model, context }) {
    const imports = Generator.ImportGenerator.from(model.mockData.stub.location)
        .add(model.types)
        .add(model.types.id.toBranded)
        .addImport({
        from: Generator.toPackageName('@postxl/utils'),
        items: [Generator.toFunctionName('Debrand')],
    });
    const modelName = Generator.toVariableName(model._conjugated.camelCase);
    const fieldAssignments = [];
    for (const field of model.fields.values()) {
        fieldAssignments.push(getFieldAssignment({ field, model, context, imports }));
    }
    return `
  ${imports.generate()}

  export const default${model.mockData.stub.name}: ${model.name} = {
    ${fieldAssignments.join(',\n')}
    }
  
  export const ${model.mockData.stub.name} = (${modelName}: Debrand<Partial<${model.name}>> = {}): ${model.name} => ({
    ...default${model.mockData.stub.name},
    ...(${modelName} as Partial<${model.name}>),
  })`;
}
function getFieldAssignment({ field, model, context, imports, }) {
    switch (field.kind) {
        case 'id':
            return `${field.name}: ${model.types.id.toBranded.name}('')`;
        case 'scalar':
            return getFieldAssignmentScalar(field);
        case 'relation':
            return getFieldAssignmentRelation({ field, context, imports });
        case 'enum':
            return getFieldAssignmentEnum({ field, context });
        case 'discriminatedUnion':
            return getFieldAssignmentDiscriminatedUnion({ field, model, context, imports });
        default:
            throw new utils_1.ExhaustiveSwitchCheck(field);
    }
}
function getFieldAssignmentScalar(field) {
    if (!field.isRequired) {
        return `${field.name}: null`;
    }
    switch (field.type) {
        case 'string':
            return `${field.name}: ''`;
        case 'number':
            return `${field.name}: 0`;
        case 'boolean':
            return `${field.name}: false`;
        case 'Date':
            return `${field.name}: new Date(2025, 1, 1)`;
        default:
            throw new utils_1.ExhaustiveSwitchCheck(field);
    }
}
function getFieldAssignmentRelation({ field, context, imports, }) {
    if (!field.isRequired) {
        return `${field.name}: null`;
    }
    const relatedModel = context.models.get(field.referencedModelName);
    imports.add(relatedModel.types.id.toBranded);
    return `${field.name}: ${relatedModel.types.id.toBranded.name}('')`;
}
function getFieldAssignmentEnum({ field, context }) {
    if (!field.isRequired) {
        return `${field.name}: null`;
    }
    const enumType = context.enums.get(field.enumName);
    const firstEntry = Array.from(enumType.members.values())[0].value;
    return `${field.name}: '${firstEntry}'`;
}
function getFieldAssignmentDiscriminatedUnion({ field, model, imports, }) {
    if (!field.isRequired) {
        return `${field.name}: null`;
    }
    const firstMember = Array.from(model.mockData.discriminatedUnions.values())[0];
    imports.addImport({
        from: firstMember.values().next().value.location,
        items: [Generator.toFunctionName('stub' + firstMember.values().next().value.name)],
    });
    return `${field.name}: stub${firstMember.values().next().value.name}({})`;
}
function generateDiscriminatedUnionStub({ context, model, discriminatedUnion, }) {
    const stubs = [];
    const imports = Generator.ImportGenerator.from(discriminatedUnion.values().next().value.location).addImport({
        from: Generator.toPackageName('@postxl/utils'),
        items: [Generator.toFunctionName('Debrand')],
    });
    for (const [memberName, stub] of discriminatedUnion) {
        stubs.push(generateMemberStub({ memberName, stub, model, imports, context }));
    }
    return `
   
  ${imports.generate()}
  
  ${stubs.join('\n')}
`;
}
function generateMemberStub({ memberName, stub, model, imports, context, }) {
    imports.addImport({
        from: Generator.toPackageName('@types'),
        items: [stub.name],
    });
    const du_fields = [];
    let fieldName = '';
    for (const field of model.fields.values()) {
        if (field.kind !== 'discriminatedUnion') {
            continue;
        }
        fieldName = field.name;
        for (const commonField of field.commonFields.values()) {
            du_fields.push(getFieldAssignment({ field: commonField, model, context, imports }));
        }
        for (const member of field.members.values()) {
            if (member.type !== memberName) {
                continue;
            }
            for (const memberField of member.fields.values()) {
                du_fields.push(getFieldAssignment({ field: memberField, model, context, imports }));
            }
        }
    }
    return `
export const defaultStub${stub.name}: ${stub.name} = {
  type: '${memberName}',
  ${du_fields.join(',\n')}
  } 

  export function stub${stub.name}(${fieldName}: Debrand<Partial<Omit<${stub.name}, 'type'>>>): ${stub.name} {
    return {
      ...defaultStub${stub.name},
      ...(${fieldName} as Partial<${stub.name}>),
    }
}
  `;
}
//# sourceMappingURL=model-stub.generator.js.map