type ReservationTranslator = (key: string, fallback?: string) => string

export function formatReservationTaskCard(
  t: ReservationTranslator,
  taskType: string | null | undefined,
  fallbackLabel?: string | null,
): string {
  return translateStableCode(t, 'cardType', taskType, 'common.unknownTaskType', fallbackLabel)
}

export function formatReservationTaskTypeSummary(
  t: ReservationTranslator,
  taskType: string | null | undefined,
  taskSubtype: string | null | undefined,
): string {
  const typeLabel = formatReservationTaskCard(t, taskType)
  const normalizedType = normalizeStableCode(taskType)
  const normalizedSubtype = normalizeStableCode(taskSubtype)
  if (!normalizedSubtype || normalizedSubtype === normalizedType) {
    return typeLabel
  }
  return `${typeLabel} / ${translateStableCode(t, 'taskSubtype', taskSubtype, 'common.unknownTaskSubtype')}`
}

export function formatReservationReadonlyReason(
  t: ReservationTranslator,
  reasonCode: string | null | undefined,
): string {
  return translateStableCode(t, 'readonlyReason', reasonCode, 'common.unknownReadonlyReason')
}

export function formatReservationMaybeStableReason(
  t: ReservationTranslator,
  reason: string | null | undefined,
  fallbackKey: string,
): string {
  if (!reason) {
    return t(fallbackKey)
  }
  if (isStableCode(reason)) {
    return formatReservationReadonlyReason(t, reason)
  }
  return reason
}

export function formatReservationActorType(t: ReservationTranslator, actorType: string): string {
  return translateStableCode(t, 'actorType', actorType, 'common.unknownActorType')
}

export function formatReservationAuditAction(t: ReservationTranslator, action: string): string {
  return translateStableCode(t, 'auditAction', action, 'common.unknownAuditAction')
}

export function formatReservationOperaOperation(
  t: ReservationTranslator,
  operationCode: string | null | undefined,
  fallbackLabel?: string | null,
): string {
  return translateStableCode(t, 'operaOperation', operationCode, 'common.unknownOperation', fallbackLabel)
}

function translateStableCode(
  t: ReservationTranslator,
  namespace: string,
  code: string | null | undefined,
  fallbackKey: string,
  fallbackLabel?: string | null,
): string {
  const normalizedCode = normalizeStableCode(code)
  if (!normalizedCode) {
    return fallbackLabel || t(fallbackKey)
  }
  return t(`${namespace}.${normalizedCode}`, fallbackLabel || t(fallbackKey))
}

function normalizeStableCode(code: string | null | undefined): string {
  if (!code) {
    return ''
  }
  return code.trim().replace(/[\s-]+/g, '_').toUpperCase()
}

function isStableCode(value: string): boolean {
  return /^[A-Z0-9_ -]+$/.test(value.trim())
}
