import { getOptionKeyHelper } from '../../helpers';
import { Option } from '../../types';
import {
  CheckboxFilterInputOption,
  CheckboxFilterInputOptionSchema,
} from '../schemas';

/**
 * Recursively maps an Option object to a CheckboxFilterInputOption with hierarchical path tracking.
 *
 * This function transforms a generic Option into a strongly-typed CheckboxFilterInputOption,
 * building a hierarchical path that uniquely identifies the option's position in the tree.
 * The mapping process:
 * - Generates a unique path by combining parent paths with the current option's key
 * - Recursively processes nested options to build the complete hierarchy
 * - Validates the result against the CheckboxFilterInputOptionSchema
 *
 * @param option - The source option object containing label, value, and optional nested values
 * @param path - Array of strings representing the path from root to the parent of this option
 * @returns A validated CheckboxFilterInputOption with complete hierarchical path information
 *
 * @example
 * ```typescript
 * const mappedOption = checkboxOptionMapping({
 *   label: 'Smartphones',
 *   value: 'smartphones',
 *   values: [
 *     { label: 'iPhone', value: 'iphone' },
 *     { label: 'Android', value: 'android' }
 *   ]
 * }, ['category', 'electronics']);
 * // Results in path: ['category', 'electronics', 'smartphones']
 * ```
 */
export function checkboxOptionMapping(
  option: Option,
  path: string[] = [],
): CheckboxFilterInputOption {
  const key = getOptionKeyHelper(option);

  return CheckboxFilterInputOptionSchema.parse({
    path: [...path, key],
    key: key, // Use value as key if not provided
    label: option.label,
    value: option.value,
    values: option.values?.map((v) => checkboxOptionMapping(v, [...path, key])),
  });
}
