from pathlib import Path
from tempfile import TemporaryDirectory

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

from clients.models import Client
from core.demo_credentials import DEMO_PORTAL_ACCOUNTS
from template_library.models import FormTemplate, ReusableTemplate


class DemoDataV7Tests(TestCase):
    def test_demo_seed_creates_complete_client_coverage_and_credentials(self):
        with TemporaryDirectory() as media_root:
            with override_settings(MEDIA_ROOT=media_root):
                call_command("seed_demo_data", reset=True, verbosity=0)
        self.assertEqual(Client.objects.count(), 8)
        self.assertFalse(Client.objects.filter(services__isnull=True).exists())
        self.assertFalse(Client.objects.filter(portal_accesses__isnull=True).exists())
        self.assertEqual(
            sum(client.portal_accesses.count() for client in Client.objects.all()),
            len(DEMO_PORTAL_ACCOUNTS),
        )
        self.assertTrue(ReusableTemplate.objects.exists())
        self.assertTrue(FormTemplate.objects.exists())
        credentials = Path(settings.BASE_DIR) / "DEMO_CLIENT_CREDENTIALS.txt"
        self.assertTrue(credentials.exists())
        content = credentials.read_text(encoding="utf-8")
        self.assertIn("cliente.acacia", content)
        self.assertIn("financeiro.horizonte", content)
