package app.closer.notifications

import android.content.Context
import android.content.SharedPreferences
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class NotificationRateLimiterTest {

    private fun createLimiter(): NotificationRateLimiter {
        val context = mockk<Context>()
        every { context.getSharedPreferences("notification_rate_limits", Context.MODE_PRIVATE) } returns InMemorySharedPreferences()
        return NotificationRateLimiter(context)
    }

    @Test
    fun `partner trigger limit allows up to two per day`() {
        val limiter = createLimiter()

        assertTrue(limiter.canSend(NotificationRateLimiter.Type.PARTNER_TRIGGER))
        limiter.record(NotificationRateLimiter.Type.PARTNER_TRIGGER)
        assertTrue(limiter.canSend(NotificationRateLimiter.Type.PARTNER_TRIGGER))
        limiter.record(NotificationRateLimiter.Type.PARTNER_TRIGGER)
        assertFalse(limiter.canSend(NotificationRateLimiter.Type.PARTNER_TRIGGER))

        assertEquals(2, limiter.count(NotificationRateLimiter.Type.PARTNER_TRIGGER))
    }

    @Test
    fun `reminder limit allows one per day`() {
        val limiter = createLimiter()

        assertTrue(limiter.canSend(NotificationRateLimiter.Type.REMINDER))
        limiter.record(NotificationRateLimiter.Type.REMINDER)
        assertFalse(limiter.canSend(NotificationRateLimiter.Type.REMINDER))

        assertEquals(1, limiter.count(NotificationRateLimiter.Type.REMINDER))
    }

    @Test
    fun `weekly total limit blocks when four notifications have been recorded`() {
        val limiter = createLimiter()

        // Record four partner-trigger notifications directly so the weekly total
        // reaches its cap independent of the daily partner-trigger limit.
        repeat(4) {
            limiter.record(NotificationRateLimiter.Type.PARTNER_TRIGGER)
        }

        assertEquals(4, limiter.totalCount())
        assertFalse(limiter.canSend(NotificationRateLimiter.Type.REMINDER))
        assertFalse(limiter.canSend(NotificationRateLimiter.Type.PARTNER_TRIGGER))
    }

    @Test
    fun `mixed types count toward weekly total`() {
        val limiter = createLimiter()

        assertTrue(limiter.canSend(NotificationRateLimiter.Type.PARTNER_TRIGGER))
        limiter.record(NotificationRateLimiter.Type.PARTNER_TRIGGER)
        assertTrue(limiter.canSend(NotificationRateLimiter.Type.REMINDER))
        limiter.record(NotificationRateLimiter.Type.REMINDER)

        assertEquals(2, limiter.totalCount())
    }

    @Test
    fun `reminder does not count toward partner daily limit`() {
        val limiter = createLimiter()

        repeat(2) {
            limiter.record(NotificationRateLimiter.Type.PARTNER_TRIGGER)
        }
        assertTrue(limiter.canSend(NotificationRateLimiter.Type.REMINDER))
        assertEquals(0, limiter.count(NotificationRateLimiter.Type.REMINDER))
    }

    private class InMemorySharedPreferences : SharedPreferences {
        private val values = mutableMapOf<String, Any>()
        private val listeners = mutableListOf<SharedPreferences.OnSharedPreferenceChangeListener>()

        override fun getAll(): Map<String, *> = values.toMap()
        override fun getString(key: String?, defValue: String?): String? = values[key] as? String ?: defValue
        override fun getStringSet(key: String?, defValues: Set<String>?): Set<String>? = values[key] as? Set<String> ?: defValues
        override fun getInt(key: String?, defValue: Int): Int = values[key] as? Int ?: defValue
        override fun getLong(key: String?, defValue: Long): Long = values[key] as? Long ?: defValue
        override fun getFloat(key: String?, defValue: Float): Float = values[key] as? Float ?: defValue
        override fun getBoolean(key: String?, defValue: Boolean): Boolean = values[key] as? Boolean ?: defValue
        override fun contains(key: String?): Boolean = key in values

        override fun edit(): SharedPreferences.Editor = InMemoryEditor()

        override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener?) {
            listener?.let { listeners.add(it) }
        }

        override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener?) {
            listener?.let { listeners.remove(it) }
        }

        private inner class InMemoryEditor : SharedPreferences.Editor {
            private val pending = mutableMapOf<String, Any?>()

            override fun putString(key: String?, value: String?): SharedPreferences.Editor = apply {
                pending[key!!] = value
            }

            override fun putStringSet(key: String?, values: Set<String>?): SharedPreferences.Editor = apply {
                pending[key!!] = values
            }

            override fun putInt(key: String?, value: Int): SharedPreferences.Editor = apply {
                pending[key!!] = value
            }

            override fun putLong(key: String?, value: Long): SharedPreferences.Editor = apply {
                pending[key!!] = value
            }

            override fun putFloat(key: String?, value: Float): SharedPreferences.Editor = apply {
                pending[key!!] = value
            }

            override fun putBoolean(key: String?, value: Boolean): SharedPreferences.Editor = apply {
                pending[key!!] = value
            }

            override fun remove(key: String?): SharedPreferences.Editor = apply {
                pending[key!!] = null
            }

            override fun clear(): SharedPreferences.Editor = apply {
                pending.clear()
                values.keys.forEach { pending[it] = null }
            }

            override fun commit(): Boolean {
                apply()
                return true
            }

            override fun apply() {
                pending.forEach { (key, value) ->
                    if (value == null) values.remove(key) else values[key] = value
                }
                pending.clear()
            }
        }
    }
}
