from __future__ import annotations

from django.test import TestCase

from core.models import ContactAvailabilitySettings, Person, PersonIdentifier, User
from core.presence.engine import (
    AvailabilitySignal,
    ensure_fading_state,
    record_inferred_signal,
    record_native_signal,
)


class PresenceEngineTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            "presence-user", "presence@example.com", "x"
        )
        self.person = Person.objects.create(user=self.user, name="Presence Person")
        self.identifier = PersonIdentifier.objects.create(
            user=self.user,
            person=self.person,
            service="signal",
            identifier="+15550001111",
        )

    def test_record_native_signal_is_a_compatibility_noop(self):
        signal = AvailabilitySignal(
            user=self.user,
            person=self.person,
            person_identifier=self.identifier,
            service="signal",
            source_kind="read_receipt",
            availability_state="available",
            confidence=0.95,
            ts=1234,
            payload={"origin": "test"},
        )
        result = record_native_signal(signal)
        self.assertIs(result, signal)

    def test_record_inferred_signal_respects_settings(self):
        ContactAvailabilitySettings.objects.update_or_create(
            user=self.user,
            defaults={"enabled": True, "inference_enabled": False},
        )
        signal = AvailabilitySignal(
            user=self.user,
            person=self.person,
            person_identifier=self.identifier,
            service="signal",
            source_kind="typing_stop",
            availability_state="fading",
            ts=1234,
        )
        self.assertIsNone(record_inferred_signal(signal))

    def test_ensure_fading_state_no_longer_persists_shadow_rows(self):
        self.assertIsNone(
            ensure_fading_state(
                user=self.user,
                person=self.person,
                person_identifier=self.identifier,
                service="signal",
                at_ts=1234,
            )
        )
