import os

from django.core.management import call_command
from django.test import TestCase
from unittest.mock import patch

# from apps.lyric.management.commands.ensure_superuser import EnsureSuperuserCommand
from apps.lyric.models import User


FAKE_ENV = {
    'DJANGO_SUPERUSER_EMAIL': 'admin@example.com',
    'DJANGO_SUPERUSER_PASSWORD': 'secret',
}


class EnsureSuperuserCommandTest(TestCase):
    def test_creates_superuser_if_none_exists(self):
        with patch.dict('os.environ', FAKE_ENV):
            call_command('ensure_superuser')
        self.assertEqual(User.objects.filter(is_superuser=True).count(), 1)

    def test_does_not_create_duplicate_if_superuser_exists(self):
        User.objects.create_superuser(email="admin@example.com", password="secret")
        with patch.dict('os.environ', FAKE_ENV):
            call_command('ensure_superuser')
        self.assertEqual(User.objects.filter(is_superuser=True).count(), 1)

    def test_skips_creation_if_credentials_not_set(self):
        with patch.dict("os.environ", {}):
            os.environ.pop("DJANGO_SUPERUSER_EMAIL", None)
            os.environ.pop("DJANGO_SUPERUSER_PASSWORD", None)
            call_command("ensure_superuser")
        self.assertEqual(User.objects.filter(is_superuser=True).count(), 0)
