import { incidentLabel } from './incidentLabels'
import type { IncidentFlagRow, IncidentLogRow } from '../../api/flags'

export function formatIncidentDatetime(iso?: string | null): string {
  if (!iso) return ''
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return String(iso)
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  const yyyy = d.getFullYear()
  const hh = String(d.getHours()).padStart(2, '0')
  const min = String(d.getMinutes()).padStart(2, '0')
  return `${mm}-${dd}-${yyyy} ${hh}:${min}`
}

export function lastUpdaterCell(flag: IncidentFlagRow): string {
  const st = flag.flag_state
  if (st === 'Open') {
    return String(flag.updated_by_open_name ?? flag.updated_by_open ?? 'N/A')
  }
  if (st === 'Closed') {
    return String(flag.updated_by_closed_name ?? flag.updated_by_closed ?? 'N/A')
  }
  if (st === 'Canceled') {
    return String(flag.updated_by_canceled_name ?? flag.updated_by_canceled ?? 'N/A')
  }
  return 'N/A'
}

export function descriptionForFlag(flag: IncidentFlagRow): string {
  const st = flag.flag_state
  if (st === 'Open') return flag.open_description ?? 'N/A'
  if (st === 'Closed') return flag.close_description ?? 'N/A'
  if (st === 'Canceled') return flag.cancel_description ?? 'N/A'
  return 'N/A'
}

export function descriptionForLog(log: IncidentLogRow): string {
  const st = log.flag_state
  if (st === 'Open' && log.open_description) return String(log.open_description)
  if (st === 'Closed' && log.close_description) return String(log.close_description)
  if (st === 'Canceled' && log.cancel_description) return String(log.cancel_description)
  return 'N/A'
}

export function incidentTypeLabel(flagKey: string | undefined): string {
  return incidentLabel(flagKey)
}
