package com.fabledsword.minstrel.playlists.data

import com.fabledsword.minstrel.cache.db.dao.PlaylistCachedCount
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class PlaylistsRepositoryCacheMergeTest {

    private fun playlist(id: String, trackCount: Int) =
        CachedPlaylistEntity(id = id, userId = "u", name = id, trackCount = trackCount)

    @Test
    fun `fully cached when every member track is resident`() {
        val out = mergePlaylistsWithCache(
            rows = listOf(playlist("p", trackCount = 3)),
            counts = listOf(PlaylistCachedCount("p", cachedCount = 3)),
        )
        assertTrue(out.single().fullyCached)
    }

    @Test
    fun `not fully cached when only some tracks are resident`() {
        val out = mergePlaylistsWithCache(
            rows = listOf(playlist("p", trackCount = 3)),
            counts = listOf(PlaylistCachedCount("p", cachedCount = 2)),
        )
        assertFalse(out.single().fullyCached)
    }

    @Test
    fun `not fully cached when no tracks are resident (missing count row)`() {
        val out = mergePlaylistsWithCache(
            rows = listOf(playlist("p", trackCount = 3)),
            counts = emptyList(),
        )
        assertFalse(out.single().fullyCached)
    }

    @Test
    fun `empty playlist is never fully cached`() {
        val out = mergePlaylistsWithCache(
            rows = listOf(playlist("p", trackCount = 0)),
            counts = listOf(PlaylistCachedCount("p", cachedCount = 0)),
        )
        assertFalse(out.single().fullyCached)
    }

    @Test
    fun `each playlist gets its own cache verdict`() {
        val out = mergePlaylistsWithCache(
            rows = listOf(playlist("full", 2), playlist("partial", 2)),
            counts = listOf(
                PlaylistCachedCount("full", cachedCount = 2),
                PlaylistCachedCount("partial", cachedCount = 1),
            ),
        )
        val byId = out.associateBy { it.id }
        assertEquals(true, byId.getValue("full").fullyCached)
        assertEquals(false, byId.getValue("partial").fullyCached)
    }
}
