package ru.forbion.f7cloud.feature.mail

import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class MailFilterRuleTest {

    @Test
    fun simple_rule_builds_web_compatible_json() {
        val rule = MailFilterRule.simple(
            name = "Работа",
            field = "subject",
            contains = "Отчёт",
            action = "fileinto",
            targetFolder = "Work",
        )
        assertEquals("Работа", rule.name)
        assertTrue(rule.enable)
        assertEquals("allof", rule.operator)
        assertEquals(listOf(Triple("subject", "contains", listOf("Отчёт"))), rule.tests)
        assertEquals("fileinto", rule.actions.single().optString("type"))
        assertEquals("Work", rule.actions.single().optString("mailbox"))
        assertTrue(rule.isSimple)
    }

    @Test
    fun markread_uses_system_flag() {
        val rule = MailFilterRule.simple("r", "from", "boss", "markread", "")
        val action = rule.actions.single()
        assertEquals("addsystemflag", action.optString("type"))
        assertTrue(action.optString("flag").contains("Seen"))
    }

    @Test
    fun withEnable_preserves_unknown_fields() {
        val raw = JSONObject(
            """{"name":"web","enable":true,"operator":"anyof","priority":20,
                "tests":[{"field":"subject","operator":"is","values":["x"]},
                         {"field":"from","operator":"contains","values":["y"]}],
                "actions":[{"type":"stop"}],"customField":"keepme"}""",
        )
        val rule = MailFilterRule(raw)
        assertFalse(rule.isSimple)
        val disabled = rule.withEnable(false)
        assertFalse(disabled.enable)
        assertEquals("keepme", disabled.raw.optString("customField"))
        assertEquals(2, disabled.tests.size)
    }
}
