from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse

from monitoring.models import WebsiteMonitor
from technical.demo_data import DEMO_MARKER
from technical.models import SSLCertificate, WordPressPlugin, WordPressSite, WordPressTheme


class WordPressDemoDataTests(TestCase):
    def setUp(self):
        self.admin = get_user_model().objects.create_superuser(
            username="admin-v94", email="admin-v94@example.com", password="StrongPass123!"
        )

    def test_command_creates_and_is_idempotent(self):
        call_command("seed_wordpress_demo_data", verbosity=0)
        first = (
            WordPressSite.objects.filter(notes__contains=DEMO_MARKER).count(),
            WordPressPlugin.objects.filter(notes__contains=DEMO_MARKER).count(),
            WordPressTheme.objects.filter(notes__contains=DEMO_MARKER).count(),
            SSLCertificate.objects.filter(notes__contains=DEMO_MARKER).count(),
            WebsiteMonitor.objects.filter(name__startswith="DEMO WP —").count(),
        )
        call_command("seed_wordpress_demo_data", verbosity=0)
        second = (
            WordPressSite.objects.filter(notes__contains=DEMO_MARKER).count(),
            WordPressPlugin.objects.filter(notes__contains=DEMO_MARKER).count(),
            WordPressTheme.objects.filter(notes__contains=DEMO_MARKER).count(),
            SSLCertificate.objects.filter(notes__contains=DEMO_MARKER).count(),
            WebsiteMonitor.objects.filter(name__startswith="DEMO WP —").count(),
        )
        self.assertEqual(first, second)
        self.assertEqual(first, (6, 34, 18, 6, 6))

    def test_admin_center_requires_superuser_and_can_seed(self):
        self.client.force_login(self.admin)
        response = self.client.get(reverse("wordpress_demo_center"))
        self.assertEqual(response.status_code, 200)
        response = self.client.post(
            reverse("wordpress_demo_center"),
            {"action": "seed", "confirmation": "DADOS DEMO WORDPRESS"},
            follow=True,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(WordPressSite.objects.filter(notes__contains=DEMO_MARKER).count(), 6)

    def test_clear_removes_only_demo_data(self):
        call_command("seed_wordpress_demo_data", verbosity=0)
        call_command("seed_wordpress_demo_data", clear=True, verbosity=0)
        self.assertFalse(WordPressSite.objects.filter(notes__contains=DEMO_MARKER).exists())
