import { z } from 'zod';

function getDefType(schema) {
  return schema._zod?.def?.type || "";
}
function getDef(schema) {
  return schema._zod?.def;
}
function getDefaultProps(schema) {
  const shape = schema.shape;
  const defaultProps = {};
  for (const key in shape) {
    if (Object.prototype.hasOwnProperty.call(shape, key)) {
      const fieldSchema = shape[key];
      const value = getDefaultValue(fieldSchema, key);
      if (value !== void 0) {
        defaultProps[key] = value;
      }
    }
  }
  return defaultProps;
}
function getDefaultValue(schema, fieldName) {
  const defType = getDefType(schema);
  const def = getDef(schema);
  if (defType === "default" && def) {
    const defaultValue = def.defaultValue;
    if (typeof defaultValue === "function") {
      return defaultValue();
    }
    return defaultValue;
  }
  if (!schema.isOptional()) {
    console.warn(`No default value set for required field "${fieldName}".`);
  }
  return void 0;
}
function addDefaultValues(schema, defaultValues) {
  const shape = schema.shape;
  const updatedShape = { ...shape };
  for (const key in defaultValues) {
    if (updatedShape[key]) {
      updatedShape[key] = updatedShape[key].default(defaultValues[key]);
    } else if (process.env.NODE_ENV !== "production") {
      console.warn(
        `Key "${key}" does not exist in the schema and will be ignored.`
      );
    }
  }
  return z.object(updatedShape);
}
function hasAnyChildrenField(schema) {
  const shape = schema.shape;
  if (!shape.children) {
    return false;
  }
  let childrenSchema = shape.children;
  let childDefType = getDefType(childrenSchema);
  while (childDefType === "optional" || childDefType === "nullable") {
    const childDef = getDef(childrenSchema);
    if (childDef?.innerType) {
      childrenSchema = childDef.innerType;
      childDefType = getDefType(childrenSchema);
    } else {
      break;
    }
  }
  return childDefType === "any";
}
function hasChildrenFieldOfTypeString(schema) {
  const shape = schema.shape;
  if (!shape.children) {
    return false;
  }
  let childrenSchema = shape.children;
  let childDefType = getDefType(childrenSchema);
  while (childDefType === "optional" || childDefType === "nullable") {
    const childDef = getDef(childrenSchema);
    if (childDef?.innerType) {
      childrenSchema = childDef.innerType;
      childDefType = getDefType(childrenSchema);
    } else {
      break;
    }
  }
  return childDefType === "string";
}

export { addDefaultValues, getDefaultProps, hasAnyChildrenField, hasChildrenFieldOfTypeString };
