import { baseCellTypeDefinitions, normalizeCellTypeName } from '../js/table-cell-type-definitions';
import type {
    KviewDetailTableColumn,
    KviewTableAlignment,
    KviewTableCellType,
} from './types';

interface CellTypeDefinition {
    alignment: KviewTableAlignment;
    numeric: boolean;
    nowrap: boolean;
}

// Alignment/numeric/nowrap come from the canonical cross-engine module
// (`js/table-cell-type-definitions`), shared with the Blade/vanilla engine so
// a cell type cannot render differently between the two runtimes.
const definitions = baseCellTypeDefinitions as Record<string, CellTypeDefinition>;

export const normalizeTableCellType = (
    type?: KviewTableCellType | null,
): Exclude<KviewTableCellType, 'checkbox' | 'percent' | 'scaled_number'> => (
    normalizeCellTypeName(type ?? undefined) as Exclude<
        KviewTableCellType,
        'checkbox' | 'percent' | 'scaled_number'
    >
);

export const tableCellTypeDefinition = (
    type?: KviewTableCellType | null,
): CellTypeDefinition => definitions[normalizeTableCellType(type)];

const dimension = (value: string | number | null | undefined): string | undefined => {
    if (value === null || value === undefined || value === '') {
        return undefined;
    }

    return typeof value === 'number' ? `${Math.max(0, value)}px` : value;
};

export const normalizeDetailTableColumn = (
    column: KviewDetailTableColumn,
): Required<Pick<KviewDetailTableColumn, 'key' | 'label' | 'type' | 'alignment' | 'numeric' | 'nowrap'>>
    & KviewDetailTableColumn => {
    const type = normalizeTableCellType(column.type);
    const definition = tableCellTypeDefinition(type);

    return {
        ...column,
        key: column.key,
        label: column.label?.trim() || column.key.replaceAll('_', ' '),
        type,
        alignment: column.alignment ?? column.align ?? definition.alignment,
        numeric: column.numeric ?? definition.numeric,
        nowrap: column.nowrap ?? definition.nowrap,
        width: dimension(column.width),
        minWidth: dimension(column.minWidth),
    };
};
