package app.closer.notifications

import app.closer.core.notifications.QuietHours
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Calendar

class QuietHoursManagerTest {

    private val manager = QuietHoursManager()

    @Test
    fun `quiet hours disabled always returns false`() {
        val quietHours = QuietHours(enabled = false, startHour = 22, endHour = 8)
        val now = calendarAt(23, 0)

        assertFalse(manager.isInQuietHours(quietHours, now))
    }

    @Test
    fun `same day window is in quiet hours`() {
        val quietHours = QuietHours(enabled = true, startHour = 10, endHour = 12)
        assertTrue(manager.isInQuietHours(quietHours, calendarAt(10, 30)))
    }

    @Test
    fun `same day window outside quiet hours returns false`() {
        val quietHours = QuietHours(enabled = true, startHour = 10, endHour = 12)
        assertFalse(manager.isInQuietHours(quietHours, calendarAt(13, 0)))
        assertFalse(manager.isInQuietHours(quietHours, calendarAt(9, 0)))
    }

    @Test
    fun `crossing midnight window detects late night quiet hours`() {
        val quietHours = QuietHours(enabled = true, startHour = 22, endHour = 8)
        assertTrue(manager.isInQuietHours(quietHours, calendarAt(23, 30)))
        assertTrue(manager.isInQuietHours(quietHours, calendarAt(22, 0)))
        assertTrue(manager.isInQuietHours(quietHours, calendarAt(3, 0)))
    }

    @Test
    fun `crossing midnight window detects non quiet hours`() {
        val quietHours = QuietHours(enabled = true, startHour = 22, endHour = 8)
        assertFalse(manager.isInQuietHours(quietHours, calendarAt(12, 0)))
        assertFalse(manager.isInQuietHours(quietHours, calendarAt(8, 1)))
        assertFalse(manager.isInQuietHours(quietHours, calendarAt(21, 59)))
    }

    @Test
    fun `boundary minutes are respected`() {
        val quietHours = QuietHours(enabled = true, startHour = 22, startMinute = 15, endHour = 8, endMinute = 30)
        assertFalse(manager.isInQuietHours(quietHours, calendarAt(22, 14)))
        assertTrue(manager.isInQuietHours(quietHours, calendarAt(22, 15)))
        assertTrue(manager.isInQuietHours(quietHours, calendarAt(8, 30)))
        assertFalse(manager.isInQuietHours(quietHours, calendarAt(8, 31)))
    }

    private fun calendarAt(hour: Int, minute: Int): Calendar {
        return Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, hour)
            set(Calendar.MINUTE, minute)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
    }
}
