import type { IconType, Option, OptionObject } from '../types'

export type { OptionObject }

export type NormalizedOption<T extends Record<string, any> = Record<string, never>> = T & {
	label: string
	value: string | number
	icon?: IconType
}

/**
 * Extract the display label from an option (string, number, or OptionObject).
 */
export function getOptionLabel(option: Option): string {
	if (option == null) { return '' }
	if (typeof option === 'object') { return (option as OptionObject).label ?? String((option as OptionObject).value ?? '') }
	return String(option)
}

/** Extract the primitive value from an option. */
export function getOptionValue(option?: Option): string | number | undefined {
	if (option == null) { return }
	if (typeof option === 'object') { return (option as OptionObject).value }
	return option as string | number
}

/** Extract the icon from an option, if present. */
export function getOptionIcon(option?: Option): IconType | undefined {
	if (option == null || typeof option !== 'object') { return }
	return (option as OptionObject).icon
}

/** Normalize any option shape to a {label, value, icon?, ...} object, preserving any extra fields. */
export function normalizeOption<T extends Record<string, any> = Record<string, never>>(option: Option | T): NormalizedOption<T> {
	if (typeof option === 'object' && option !== null) {
		const obj = option as any
		return { ...obj, label: obj.label ?? String(obj.value ?? ''), value: obj.value } as NormalizedOption<T>
	}
	return { label: String(option), value: option as string | number } as NormalizedOption<T>
}
