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

from .models import FormTemplate, FormTemplateField, ReusableTemplate, TemplateUsage


class TemplateLibraryTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user = get_user_model().objects.create_superuser(
            username="admin.templates",
            email="admin@example.com",
            password="Templates-2026!",
        )
        call_command("seed_template_library", verbosity=0)

    def setUp(self):
        self.client.force_login(self.user)

    def test_template_center_and_previews_load(self):
        response = self.client.get(reverse("template_center"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Centro de templates")

        reusable = ReusableTemplate.objects.first()
        response = self.client.get(reverse("reusable_template_preview", args=(reusable.pk,)))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(TemplateUsage.objects.filter(reusable_template=reusable).exists())

        form = FormTemplate.objects.first()
        response = self.client.get(reverse("form_template_preview", args=(form.pk,)))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, form.name)
        self.assertTrue(TemplateUsage.objects.filter(form_template=form).exists())

    def test_safe_render_preserves_unknown_variables(self):
        template = ReusableTemplate.objects.first()
        template.body_template = "Olá {cliente}. Código: {variavel_desconhecida}."
        template.example_context = {"cliente": "Cliente Teste"}
        self.assertEqual(
            template.render_body(),
            "Olá Cliente Teste. Código: {variavel_desconhecida}.",
        )

    def test_select_field_requires_options(self):
        form = FormTemplate.objects.first()
        field = FormTemplateField(
            form_template=form,
            label="Seleção",
            key="selection-test",
            field_type=FormTemplateField.FieldType.SELECT,
            options="",
        )
        with self.assertRaises(ValidationError):
            field.full_clean()
