"""Tests for rules app models."""

import pytest

from rules.models import Rule

from .factories import RuleFactory


@pytest.mark.django_db
class TestRule:
    """Tests for the Rule model."""

    def test_create_rule(self):
        """Test creating a rule with the factory."""
        rule = RuleFactory()
        assert rule.pk is not None
        assert rule.name.startswith("Rule")
        assert rule.workspace is not None

    def test_rule_str(self):
        """Test rule string representation."""
        rule = RuleFactory(name="Auto-tag contributors")
        assert str(rule) == "Auto-tag contributors"

    def test_rule_default_values(self):
        """Test rule default values."""
        rule = RuleFactory()
        assert rule.priority == 0
        assert rule.is_enabled is True
        assert rule.description == ""
        assert rule.predicate == {}
        assert rule.action_params == {}

    def test_rule_with_custom_priority(self):
        """Test rule with custom priority."""
        rule = RuleFactory(priority=10)
        assert rule.priority == 10

    def test_rule_can_be_disabled(self):
        """Test rule can be disabled."""
        rule = RuleFactory(is_enabled=False)
        assert rule.is_enabled is False

    def test_rule_with_predicate(self):
        """Test rule with predicate JSON."""
        predicate = {"field": "source", "operator": "equals", "value": "github"}
        rule = RuleFactory(predicate=predicate)
        assert rule.predicate == predicate

    def test_rule_with_action_params(self):
        """Test rule with action params JSON."""
        action_params = {"tag": "contributor", "notify": True}
        rule = RuleFactory(action_params=action_params)
        assert rule.action_params == action_params

    def test_rule_ordering(self):
        """Test rules are ordered by priority descending, then by id."""
        workspace = RuleFactory().workspace
        rule1 = RuleFactory(workspace=workspace, priority=5)
        rule2 = RuleFactory(workspace=workspace, priority=10)
        rule3 = RuleFactory(workspace=workspace, priority=5)

        rules = list(Rule.objects.filter(workspace=workspace))
        # Higher priority first
        assert rules[0] == rule2
        # Same priority: ordered by id
        assert rules[1] == rule1
        assert rules[2] == rule3

    def test_rule_has_timestamps(self):
        """Test that rule has created_at and updated_at."""
        rule = RuleFactory()
        assert rule.created_at is not None
        assert rule.updated_at is not None

    def test_rule_belongs_to_workspace(self):
        """Test rule belongs to a workspace."""
        rule = RuleFactory()
        assert rule.workspace is not None
        assert rule in rule.workspace.rules.all()
