import uuid

from django.conf import settings
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.core.checks import run_checks
from django.test import SimpleTestCase, TestCase
from django.urls import resolve, reverse


class FoundationTests(SimpleTestCase):
    def test_system_checks(self):
        self.assertEqual(run_checks(), [])

    def test_custom_user_configuration(self):
        self.assertEqual(settings.AUTH_USER_MODEL, "accounts.User")
        self.assertEqual(get_user_model()._meta.label, "accounts.User")
        self.assertIsInstance(admin.site._registry[get_user_model()], UserAdmin)

    def test_health(self):
        response = self.client.get(reverse("health"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"status": "ok"})

    def test_health_exposes_no_configuration(self):
        with self.settings(SECRET_KEY="sensitive-test-sentinel", DEBUG=False):
            response = self.client.get(reverse("health"))
        self.assertEqual(response.content, b'{"status": "ok"}')
        self.assertNotIn(b"sensitive-test-sentinel", response.content)

    def test_admin_resolves(self):
        self.assertEqual(resolve("/admin/").view_name, "admin:index")


class UserTests(TestCase):
    def test_create_user(self):
        user = get_user_model().objects.create_user(username="technician", password="test-only-password")
        user.refresh_from_db()
        self.assertIsInstance(user.pk, uuid.UUID)
        self.assertTrue(user.check_password("test-only-password"))
        self.assertNotEqual(user.password, "test-only-password")
        self.assertFalse(user.is_staff)
        self.assertFalse(user.is_superuser)

    def test_create_superuser(self):
        user = get_user_model().objects.create_superuser(username="admin", password="test-only-password")
        self.assertTrue(user.is_staff)
        self.assertTrue(user.is_superuser)
