import { z } from "zod";
import { keyStringFromKeyChain, isMyKeyChainItem } from "./keyChain.js";
function validationErrorsByKeyChain(rootErrors = [], keyChain = []) {
  if (!keyChain.length) {
    return [];
  }
  const keyChainAttrStringDots = keyStringFromKeyChain(keyChain, "dots");
  const keyChainAttrStringSquareArray = keyStringFromKeyChain(keyChain, "brackets");
  return rootErrors.filter((error) => isMyKeyChainItem(error.key, keyChainAttrStringDots, keyChainAttrStringSquareArray));
}
function clientValidationReducer(state, action) {
  switch (action.type) {
    case "add-validation":
      return [...state, ...action.errors];
    case "clear-validation":
      return state.filter((s) => {
        var _a, _b;
        return !((!action.key || action.key === s.key) && (!((_a = action.identifiers) == null ? void 0 : _a.length) || ((_b = action.identifiers) == null ? void 0 : _b.some((i) => i === s.identifier))));
      });
    default:
      return state;
  }
}
function zodFromValidationSchema(schema) {
  const isArrayOfZod = (arrayItem) => {
    return !!(arrayItem == null ? void 0 : arrayItem.itemSchema);
  };
  const isObjectOfZod = (objectItem) => {
    return !!(objectItem == null ? void 0 : objectItem.schema);
  };
  const unpackObject = (incomingObject) => {
    return Object.keys(incomingObject).reduce((sch, key) => ({
      ...sch,
      // eslint-disable-next-line @typescript-eslint/no-use-before-define -- these two require eachother
      [key]: unpackValueToZod(incomingObject[key])
    }), {});
  };
  const unpackValueToZod = (incomingToZod) => {
    if (isArrayOfZod(incomingToZod)) {
      const arrayInner = z.array(unpackValueToZod(incomingToZod.itemSchema));
      return incomingToZod.opts ? incomingToZod.opts(arrayInner) : arrayInner;
    }
    if (isObjectOfZod(incomingToZod)) {
      const obInner = unpackValueToZod(incomingToZod.schema);
      return incomingToZod.opts ? incomingToZod.opts(obInner) : obInner;
    }
    if (incomingToZod._def) {
      return incomingToZod;
    }
    if (typeof incomingToZod === "object") {
      return z.object(unpackObject(incomingToZod));
    }
    return unpackValueToZod(incomingToZod);
  };
  if (isArrayOfZod(schema) || isObjectOfZod(schema)) {
    return unpackValueToZod(schema);
  }
  return z.object(unpackObject(schema));
}
const getMyZodErrors = (errors, keyChainString) => {
  return errors.filter((e) => keyChainString ? isMyKeyChainItem(keyStringFromKeyChain(e.path, "dots"), keyChainString) : true).map((e) => ({
    key: keyStringFromKeyChain(e.path, "dots"),
    message: e.message
  }));
};
const rootValidationSchemaIsFunction = (schema) => {
  return typeof schema === "function";
};
export {
  clientValidationReducer,
  getMyZodErrors,
  rootValidationSchemaIsFunction,
  validationErrorsByKeyChain,
  zodFromValidationSchema
};
//# sourceMappingURL=validation.js.map
