// function isEmpty(v) {
//   return v === undefined || v === null || (typeof v === "string" && v.trim() === "");
// }

// function validateFieldValue(inputValue, rule) {
//   if ((rule.optional === "N" || rule.optional === false) && isEmpty(inputValue)) {
//     throw new Error(`${rule.parameter_name} is required`);
//   }
//   if (isEmpty(inputValue)) return true;

//   if (rule.data_type) {
//     const dt = rule.data_type.toLowerCase();
//     if (dt === "numeric" && isNaN(Number(inputValue))) {
//       throw new Error(`${rule.parameter_name} must be numeric`);
//     }
//     if (dt === "alphanumeric" && !/^[A-Za-z0-9\s\-_.@\/()&,;[\]\\]*$/.test(String(inputValue))) {
//       throw new Error(`${rule.parameter_name} must be alphanumeric`);
//     }
//   }

//   if (rule.regex) {
//     try {
//       const re = new RegExp(rule.regex.replace(/\\\\/g, "\\"));
//       if (!re.test(String(inputValue))) {
//         throw new Error(rule.error_message || `${rule.parameter_name} invalid`);
//       }
//     } catch (e) {
//       console.warn("Invalid regex:", rule.regex);
//     }
//   }

//   return true;
// }

// module.exports = { validateFieldValue, isEmpty };


class ValidationError extends Error {
  constructor(message, code = 4008) {
    super(message);
    this.name = "ValidationError";
    this.code = code;
  }
}

function isEmpty(value) {
  return (
    value === undefined ||
    value === null ||
    (typeof value === "string" && value.trim() === "")
  );
}

function validateFieldValue(inputValue, rule = {}) {
  const field = rule.parameter_name || "Field";

  // Required check
  if ((rule.optional === "N" || rule.optional === false) && isEmpty(inputValue)) {
    throw new ValidationError(`${field} is required`);
  }
  if (isEmpty(inputValue)) return true;

  const value = String(inputValue);

  // Data type check
  if (rule.data_type) {
    const dt = rule.data_type.toLowerCase();
    if (dt === "numeric" && isNaN(Number(value))) {
      throw new ValidationError(`${field} must be numeric`);
    }
    if (dt === "alphanumeric" && !/^[A-Za-z0-9\s\-_.@\/()&,;[\]\\]*$/.test(value)) {
      throw new ValidationError(`${field} must be alphanumeric`);
    }
  }

  // Length checks
  if (rule.min_length && value.length < rule.min_length) {
    throw new ValidationError(`${field} must have at least ${rule.min_length} characters`);
  }
  if (rule.max_length && value.length > rule.max_length) {
    throw new ValidationError(`${field} must not exceed ${rule.max_length} characters`);
  }

  // Regex validation
  if (rule.regex) {
    try {
      const re = new RegExp(rule.regex);
      if (!re.test(value)) {
        throw new ValidationError(rule.error_message || `${field} format invalid`);
      }
    } catch (err) {
      console.warn("Invalid regex in config:", rule.regex);
    }
  }

  return true;
}

module.exports = { validateFieldValue, isEmpty, ValidationError };
