from __future__ import annotations

from io import StringIO

from django.core.management import call_command
from django.test import TestCase, override_settings

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


@override_settings(CONVERSATION_EVENT_RETENTION_DAYS=90)
class PruneBehavioralOrmDataCommandTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="prune-user",
            email="prune@example.com",
            password="x",
        )
        self.person = Person.objects.create(user=self.user, name="Prune Person")
        self.identifier = PersonIdentifier.objects.create(
            user=self.user,
            person=self.person,
            service="signal",
            identifier="+15555550111",
        )
        self.session = ChatSession.objects.create(
            user=self.user,
            identifier=self.identifier,
        )

    def test_prune_command_deletes_old_shadow_rows(self):
        ConversationEvent.objects.create(
            user=self.user,
            session=self.session,
            ts=1000,
            event_type="message_created",
            direction="in",
            origin_transport="signal",
        )

        out = StringIO()
        call_command("prune_behavioral_orm_data", stdout=out)

        self.assertEqual(0, ConversationEvent.objects.count())
        self.assertIn("prune-behavioral-orm-data", out.getvalue())

    def test_prune_command_supports_dry_run(self):
        ConversationEvent.objects.create(
            user=self.user,
            session=self.session,
            ts=1000,
            event_type="message_created",
            direction="in",
            origin_transport="signal",
        )

        out = StringIO()
        call_command("prune_behavioral_orm_data", "--dry-run", stdout=out)

        self.assertEqual(1, ConversationEvent.objects.count())
        self.assertIn("dry_run=True", out.getvalue())

    def test_prune_command_can_limit_tables(self):
        ConversationEvent.objects.create(
            user=self.user,
            session=self.session,
            ts=1000,
            event_type="message_created",
            direction="in",
            origin_transport="signal",
        )

        call_command(
            "prune_behavioral_orm_data",
            "--tables",
            "conversation_events",
            stdout=StringIO(),
        )

        self.assertEqual(0, ConversationEvent.objects.count())
