package ru.forbion.f7cloud.feature.calendar

import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder

/**
 * Кэш «сырых» REPORT-ответов CalDAV: CTag совпал → XML с диска; изменился/пусто → null.
 */
class CalendarEventsCacheTest {

    @get:Rule
    val tmp = TemporaryFolder()

    private fun cache() = CalendarEventsCache(tmp.newFolder("caldav"))

    @Test fun hit_when_ctag_matches() {
        val c = cache()
        c.put("acc", "/cal/personal/", "r1", "ctag-1", "<xml>events</xml>")
        assertEquals("<xml>events</xml>", c.get("acc", "/cal/personal/", "r1", "ctag-1"))
    }

    @Test fun miss_when_ctag_changed() {
        val c = cache()
        c.put("acc", "/cal/personal/", "r1", "ctag-1", "<xml/>")
        assertNull(c.get("acc", "/cal/personal/", "r1", "ctag-2"))
    }

    @Test fun miss_on_blank_ctag_and_unknown_range() {
        val c = cache()
        c.put("acc", "/cal/personal/", "r1", "", "<xml/>") // пустой ctag не кэшируется
        assertNull(c.get("acc", "/cal/personal/", "r1", ""))
        assertNull(c.get("acc", "/cal/personal/", "other-range", "ctag-1"))
    }

    @Test fun entries_are_isolated_by_account_calendar_range() {
        val c = cache()
        c.put("acc1", "/cal/a/", "r1", "t", "<a1/>")
        c.put("acc2", "/cal/a/", "r1", "t", "<a2/>")
        c.put("acc1", "/cal/b/", "r1", "t", "<b1/>")
        assertEquals("<a1/>", c.get("acc1", "/cal/a/", "r1", "t"))
        assertEquals("<a2/>", c.get("acc2", "/cal/a/", "r1", "t"))
        assertEquals("<b1/>", c.get("acc1", "/cal/b/", "r1", "t"))
    }

    @Test fun multiline_xml_preserved() {
        val c = cache()
        val xml = "<multistatus>\n  <response>\n    <href>/e1.ics</href>\n  </response>\n</multistatus>"
        c.put("acc", "/cal/", "r", "ct", xml)
        assertEquals(xml, c.get("acc", "/cal/", "r", "ct"))
    }
}
