import { Input, InputType } from '../../types';
import { CheckboxFilterInput, CheckboxFilterInputSchema } from '../schemas';
import { checkboxOptionMapping } from './checkbox-option.mapping';

/**
 * Maps an Input object to a CheckboxFilterInput object with support for hierarchical options.
 *
 * This function transforms a generic Input object into a strongly-typed CheckboxFilterInput,
 * handling nested checkbox options, selection limits, and tracking selection states. The mapping process:
 * - Validates the input against the CheckboxFilterInputSchema
 * - Maps the maximum options limit from `input.options?.max` to `maxOptions` property
 * - Recursively maps nested options with proper path tracking
 * - Extracts selected values from the option tree
 *
 * @param group - The group identifier that this input belongs to
 * @param input - The source input object containing checkbox configuration
 * @returns A validated CheckboxFilterInput object with hierarchical options and optional selection limits
 *
 * @example
 * ```typescript
 * const checkboxInput = checkboxFilterInputMapping('filters', {
 *   key: 'category',
 *   label: 'Product Category',
 *   type: 'checkbox',
 *   options: {
 *     max: 3, // Maps to maxOptions: 3
 *     values: [
 *       { value: 'electronics', label: 'Electronics', selected: true },
 *       { value: 'clothing', label: 'Clothing' }
 *     ]
 *   }
 * });
 * ```
 */
export function checkboxFilterInputMapping(
  group: string,
  input: Input,
): CheckboxFilterInput {
  return CheckboxFilterInputSchema.parse({
    group,
    key: input.key,
    label: input.label,
    description: input.description,
    type: InputType.Checkbox,
    defaultValue: input.value,
    maxOptions: input.options?.max,
    target: input.target,
    options: input.options?.values?.map((v) =>
      checkboxOptionMapping(v, [group, input.key]),
    ),
    selected:
      input.options?.values
        ?.filter((option) => option.selected)
        .map((option) => option.value) || [],
  });
}
