from django.test import TestCase
from django.urls import reverse

from core.models import ChatSession, Message, Person, PersonIdentifier, User


class SystemProjectionShadowAPITests(TestCase):
    def setUp(self):
        self.user = User.objects.create_superuser(
            username="sys-shadow-admin",
            email="sys-shadow@example.com",
            password="pw",
        )
        person = Person.objects.create(user=self.user, name="System Shadow Person")
        identifier = PersonIdentifier.objects.create(
            user=self.user,
            person=person,
            service="signal",
            identifier="+15553332222",
        )
        self.session = ChatSession.objects.create(user=self.user, identifier=identifier)
        self.client.force_login(self.user)

    def test_projection_shadow_requires_session_id(self):
        response = self.client.get(reverse("system_projection_shadow"))
        self.assertEqual(400, response.status_code)
        payload = response.json()
        self.assertFalse(payload.get("ok"))
        self.assertEqual("session_id_required", payload.get("error"))

    def test_projection_shadow_includes_cause_summary_and_samples(self):
        Message.objects.create(
            user=self.user,
            session=self.session,
            ts=1700000000000,
            sender_uuid="+15553332222",
            text="row-without-event",
        )
        response = self.client.get(
            reverse("system_projection_shadow"),
            {"session_id": str(self.session.id), "detail_limit": 10},
        )
        self.assertEqual(200, response.status_code)
        payload = response.json()
        self.assertTrue(payload.get("ok"))
        self.assertIn("cause_summary", payload)
        self.assertIn("cause_samples", payload)
        cause_summary = dict(payload.get("cause_summary") or {})
        cause_samples = dict(payload.get("cause_samples") or {})
        self.assertIn("missing_event_write", cause_summary)
        self.assertIn("missing_event_write", cause_samples)
        self.assertGreaterEqual(int(cause_summary.get("missing_event_write") or 0), 1)
