from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
from unittest.mock import patch

from domains.models import Domain
from core.models import SystemSettings


User = get_user_model()


class DNSCheckTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='u1', email='u1@example.com', password='p')
        SystemSettings.objects.create(cname_template='{sub}.cdn.example.com')
        self.domain = Domain.objects.create(
            user=self.user,
            name='example.com',
            status=Domain.STATUS_PENDING,
            cname_targets={'www.example.com': 'www.cdn.example.com'},
        )

    def test_dns_check_updates_status(self):
        c = Client()
        c.login(username='u1', password='p')
        with patch('core.utils.resolve_cname', return_value=['www.cdn.example.com']):
            resp = c.post(reverse('domains:check_dns', kwargs={'domain_id': self.domain.id}))
        self.assertEqual(resp.status_code, 200)
        self.domain.refresh_from_db()
        self.assertEqual(self.domain.status, Domain.STATUS_ACTIVE)
