export type UiGridStatusSemantic =
  | 'ready' | 'info' | 'pending' | 'processing' | 'completed'
  | 'warning' | 'hold' | 'error' | 'cancelled' | 'disabled'

export interface UiGridStatusDefinition {
  value: string
  label: string
  semantic: UiGridStatusSemantic
}

export interface UiGridStatusMap {
  definitions: readonly UiGridStatusDefinition[]
  unknownLabel?: string
}

export interface ResolvedUiGridStatus {
  rawValue: string
  label: string
  semantic: UiGridStatusSemantic
  unknown: boolean
}

/** Preserves the API/domain value and resolves only presentation metadata. */
export function resolveUiGridStatus(map: UiGridStatusMap | undefined, value: unknown): ResolvedUiGridStatus {
  const rawValue = value == null ? '' : String(value)
  const definition = map?.definitions.find(item => item.value === rawValue)
  if (definition) return { rawValue, label: definition.label, semantic: definition.semantic, unknown: false }
  return {
    rawValue,
    label: `${map?.unknownLabel ?? '정의되지 않음'} · ${rawValue || '빈 값'}`,
    semantic: 'warning',
    unknown: true,
  }
}

/** Filters on the visible label while preserving the canonical row value. */
export function matchesUiGridStatus(map: UiGridStatusMap | undefined, value: unknown, query: string): boolean {
  const normalizedQuery = query.trim().toLocaleLowerCase()
  if (!normalizedQuery) return true
  const resolved = resolveUiGridStatus(map, value)
  return resolved.label.toLocaleLowerCase().includes(normalizedQuery)
}

/** Export status labels, but keep non-status values unchanged at the boundary. */
export function formatUiGridCellForExport(map: UiGridStatusMap | undefined, value: unknown): string {
  return map ? resolveUiGridStatus(map, value).label : value == null ? '' : String(value)
}
