import { Input, InputType } from '../../types';
import {
  NumberRangeFilterInput,
  NumberRangeFilterInputSchema,
} from '../schemas';

export function numberRangeFilterInputMapping(
  group: string,
  input: Input,
): NumberRangeFilterInput {
  // Extract minValue and maxValue, removing trailing dashes
  const minValueRaw = input.options?.values?.[0]?.minValue;
  const maxValueRaw = input.options?.values?.[0]?.maxValue;
  
  // Parse minValue: "1-" becomes 1, undefined stays undefined
  const minDefault = minValueRaw
    ? Number(minValueRaw.replace(/-/g, ''))
    : undefined;
  
  // Parse maxValue: "-100" becomes 100, undefined stays undefined  
  const maxDefault = maxValueRaw
    ? Number(maxValueRaw.replace(/-/g, ''))
    : undefined;

  return NumberRangeFilterInputSchema.parse({
    group,
    key: input.key,
    label: input.label,
    description: input.description,
    type: InputType.NumberRange,
    target: input.target,
    // Use value if present (for pre-filled values), otherwise use minValue as default
    min: input.options?.values?.[0]?.value
      ? Number(input.options?.values?.[0]?.value)
      : minDefault,
    max: input.options?.values?.[1]?.value
      ? Number(input.options?.values?.[1]?.value)
      : maxDefault,
    // Store the constraints for validation
    minValue: minDefault,
    maxValue: maxDefault,
    minLabel: input.options?.values?.[0]?.label || 'Min',
    maxLabel: input.options?.values?.[1]?.label || 'Max',
  });
}
