/**
 * Parse text content and replace {variable.field} expressions with actual data values
 * @param {string} text - Text containing binding expressions like "Owner: {owner.name}"
 * @param {object} data - Data object containing the values to bind
 * @returns {string} - Text with bindings resolved
 */
export function parseBindings(text, data) {
  if (!text || typeof text !== 'string') {
    return text || '';
  }

  if (!data || typeof data !== 'object') {
    return text;
  }

  // Regex to match {variable.field.nested} patterns
  const bindingRegex = /\{([a-zA-Z0-9_.]+)\}/g;

  return text.replace(bindingRegex, (match, path) => {
    const value = resolveNestedPath(data, path);

    // If value is found, return it; otherwise keep the original binding
    if (value !== undefined && value !== null) {
      return String(value);
    }

    return match; // Keep {variable} if not found
  });
}

/**
 * Resolve a nested path in an object (e.g., "owner.contact.name")
 * @param {object} obj - The object to traverse
 * @param {string} path - Dot-separated path (e.g., "owner.name")
 * @returns {*} - The resolved value or undefined
 */
function resolveNestedPath(obj, path) {
  const keys = path.split('.');
  let current = obj;

  for (const key of keys) {
    if (current === null || current === undefined) {
      return undefined;
    }

    if (!current.hasOwnProperty(key)) {
      return undefined;
    }

    current = current[key];
  }

  return current;
}

/**
 * Check if text contains any binding expressions
 * @param {string} text - Text to check
 * @returns {boolean} - True if text contains bindings
 */
export function hasBindings(text) {
  if (!text || typeof text !== 'string') {
    return false;
  }

  return /\{[a-zA-Z0-9_.]+\}/.test(text);
}

/**
 * Extract all binding paths from text
 * @param {string} text - Text to analyze
 * @returns {string[]} - Array of binding paths (e.g., ["owner.name", "vessel.id"])
 */
export function extractBindingPaths(text) {
  if (!text || typeof text !== 'string') {
    return [];
  }

  const bindingRegex = /\{([a-zA-Z0-9_.]+)\}/g;
  const paths = [];
  let match;

  while ((match = bindingRegex.exec(text)) !== null) {
    paths.push(match[1]);
  }

  return paths;
}
