package com.doctate.watch.presentation

import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale

private val timeFormat = DateTimeFormatter.ofPattern("HH:mm", Locale.getDefault())
private val dateTimeFormat = DateTimeFormatter.ofPattern("dd.MM.yy - HH:mm", Locale.getDefault())

/**
 * German relative time label for case timestamps.
 *
 * - < 60 min → "Vor N Minuten" (with singular/plural and "Gerade eben" for 0)
 * - today   → "HH:mm"
 * - yesterday → "Gestern - HH:mm"
 * - older   → "dd.MM.yy - HH:mm"
 *
 * Shared by CaseListScreen rows and CaseDetailScreen header so the formats
 * never drift apart.
 */
internal fun formatTime(epochMs: Long): String {
    val ageMinutes = (System.currentTimeMillis() - epochMs) / 60_000L
    if (ageMinutes in 0L until 60L) {
        return when (ageMinutes) {
            0L -> "Gerade eben"
            1L -> "Vor 1 Minute"
            else -> "Vor $ageMinutes Minuten"
        }
    }
    val zone = ZoneId.systemDefault()
    val created = Instant.ofEpochMilli(epochMs).atZone(zone)
    val createdDate = created.toLocalDate()
    val today = LocalDate.now(zone)
    return when (createdDate) {
        today -> created.format(timeFormat)
        today.minusDays(1) -> "Gestern - ${created.format(timeFormat)}"
        else -> created.format(dateTimeFormat)
    }
}
