from datetime import timedelta
from io import StringIO

from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone

from ..constants import MODE_ADMIN, MODE_CUSTOMER
from ..models import AiAssistantSession


class AiAssistantCleanupCommandTests(TestCase):
    def setUp(self):
        self.old_customer = AiAssistantSession.objects.create(
            site_id=77,
            mode=MODE_CUSTOMER,
            visitor_id="visitor-old",
        )
        self.old_admin = AiAssistantSession.objects.create(
            site_id=77,
            mode=MODE_ADMIN,
        )
        self.recent_customer = AiAssistantSession.objects.create(
            site_id=77,
            mode=MODE_CUSTOMER,
        )
        old_timestamp = timezone.now() - timedelta(days=45)
        AiAssistantSession.objects.filter(id=self.old_customer.id).update(
            updated_at=old_timestamp
        )
        AiAssistantSession.objects.filter(id=self.old_admin.id).update(
            updated_at=old_timestamp
        )

    def test_cleanup_command_dry_run_does_not_mutate(self):
        out = StringIO()
        call_command(
            "cleanup_ai_assistant",
            "--days=30",
            "--mode=customer",
            stdout=out,
        )
        self.old_customer.refresh_from_db()
        self.old_admin.refresh_from_db()
        self.assertEqual(self.old_customer.status, "open")
        self.assertEqual(self.old_admin.status, "open")
        self.assertIn("Dry run: True", out.getvalue())
