package com.fabledsword.minstrel.cache.db

import androidx.room.TypeConverter
import kotlinx.datetime.Instant

/**
 * Source category for a cached audio file. Mirrors the Drift `CacheSource`
 * enum used by the Flutter client's `audio_cache_index` table 1:1.
 *
 * - `MANUAL`: user explicitly pinned (e.g. "save for offline")
 * - `AUTO_LIKED`: auto-cached because the track is liked
 * - `AUTO_PLAYLIST`: auto-cached because it's in a pinned playlist
 * - `AUTO_PREFETCH`: pre-warmed by background prefetch heuristics
 * - `INCIDENTAL`: cached as a side effect of playback streaming
 *
 * Eviction priority order (first to evict): INCIDENTAL → AUTO_PREFETCH
 * → AUTO_PLAYLIST → AUTO_LIKED → MANUAL.
 */
enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCIDENTAL }

/**
 * Cross-cutting Room type converters. Registered on `@Database` via
 * `@TypeConverters(MinstrelTypeConverters::class)`.
 *
 * `kotlinx.datetime.Instant` ↔ `Long` epoch millis: the same convention the
 * Flutter client uses (Drift `text()` column with ISO-8601 strings would
 * also work but Long is leaner; we don't need human-readable rows in the
 * SQLite file).
 */
class MinstrelTypeConverters {
    @TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds()

    @TypeConverter fun longToInstant(l: Long?): Instant? =
        l?.let { Instant.fromEpochMilliseconds(it) }

    @TypeConverter fun sourceToName(s: CacheSource?): String? = s?.name

    @TypeConverter fun nameToSource(n: String?): CacheSource? =
        n?.let { CacheSource.valueOf(it) }
}
