/** Minimal Zod → JSON Schema converter for the OpenAPI document (covers the types used in request bodies). */
import type { ZodTypeAny } from "zod";

export function zodToJsonSchema(t: ZodTypeAny): Record<string, unknown> {
  const d = (t as any)._def;
  switch (d.typeName) {
    case "ZodObject": {
      const shape = d.shape();
      const properties: Record<string, unknown> = {};
      const required: string[] = [];
      for (const [k, v] of Object.entries(shape) as [string, ZodTypeAny][]) {
        properties[k] = zodToJsonSchema(v);
        if (!v.isOptional()) required.push(k);
      }
      return { type: "object", properties, ...(required.length ? { required } : {}) };
    }
    case "ZodString": return { type: "string", ...(d.checks?.some((c: any) => c.kind === "email") ? { format: "email" } : {}), ...(d.checks?.some((c: any) => c.kind === "uuid") ? { format: "uuid" } : {}), ...(d.checks?.some((c: any) => c.kind === "datetime") ? { format: "date-time" } : {}) };
    case "ZodNumber": return { type: d.checks?.some((c: any) => c.kind === "int") ? "integer" : "number" };
    case "ZodBoolean": return { type: "boolean" };
    case "ZodArray": return { type: "array", items: zodToJsonSchema(d.type) };
    case "ZodEnum": return { type: "string", enum: d.values };
    case "ZodLiteral": return { const: d.value };
    case "ZodOptional": case "ZodNullable": case "ZodDefault": case "ZodEffects": return zodToJsonSchema(d.innerType ?? d.schema);
    case "ZodRecord": return { type: "object", additionalProperties: d.valueType ? zodToJsonSchema(d.valueType) : true };
    case "ZodUnion": return { oneOf: d.options.map(zodToJsonSchema) };
    default: return {};
  }
}
