"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.generateJsonSeedUtils = generateJsonSeedUtils;
const Generator = __importStar(require("@postxl/generator"));
function generateJsonSeedUtils(context) {
    const { dataModel } = context.decoders;
    const imports = Generator.ImportGenerator.from(context.seed.readJsonSeedData.location)
        .addType(dataModel.decodedType)
        .add(dataModel.decoder.zodDecoder);
    return `
import { readFile } from 'node:fs/promises'

${imports.generate()}

/**
 * Reads a JSON seed data file, validates it against the DataModel schema,
 * and optionally extracts a specific scenario.
 *
 * When \`scenario\` is provided, the file is expected to contain a \`scenarios\` object
 * and the data is read from \`scenarios[scenario].data\`.
 * When \`scenario\` is omitted, the entire parsed JSON is validated and returned.
 *
 * @param filename - Absolute path to the JSON file
 * @param scenario - Optional scenario name to extract
 * @returns The validated and parsed seed data
 */
export async function ${context.seed.readJsonSeedData.name}(filename: string, scenario?: string): Promise<${dataModel.decodedType.name}> {
  let fileContent: string
  try {
    fileContent = await readFile(filename, 'utf-8')
  } catch (error) {
    throw new Error(
      \`Failed to read JSON seed file "\${filename}": \${error instanceof Error ? error.message : String(error)}\`,
    )
  }

  let parsed: unknown
  try {
    parsed = JSON.parse(fileContent)
  } catch (error) {
    throw new Error(
      \`Failed to parse JSON seed file "\${filename}": \${error instanceof Error ? error.message : String(error)}\`,
    )
  }

  const data = extractData(parsed, filename, scenario)

  try {
    return ${dataModel.decoder.zodDecoder.name}.parse(data) as ${dataModel.decodedType.name}
  } catch (error) {
    throw new Error(
      \`Invalid seed data in "\${filename}"\${scenario ? \` (scenario "\${scenario}")\` : ''}: \${error instanceof Error ? error.message : String(error)}\`,
    )
  }
}

function extractData(parsed: unknown, filename: string, scenario?: string): unknown {
  if (!scenario) {
    return parsed
  }

  if (!parsed || typeof parsed !== 'object' || !('scenarios' in parsed)) {
    throw new Error(
      \`JSON seed file "\${filename}" does not contain a "scenarios" object, but scenario "\${scenario}" was requested.\`,
    )
  }

  const scenarios = (parsed as Record<string, unknown>).scenarios
  if (!scenarios || typeof scenarios !== 'object') {
    throw new Error(
      \`JSON seed file "\${filename}" has an invalid "scenarios" field (expected an object).\`,
    )
  }

  const scenarioEntry = (scenarios as Record<string, unknown>)[scenario]
  if (!scenarioEntry) {
    const available = Object.keys(scenarios as Record<string, unknown>).join(', ')
    throw new Error(
      \`Scenario "\${scenario}" not found in "\${filename}". Available scenarios: \${available}\`,
    )
  }

  return (scenarioEntry as Record<string, unknown>).data
}`;
}
//# sourceMappingURL=json-seed-utils.generator.js.map