import os

from django.contrib.auth import get_user_model
from django.db.utils import OperationalError, ProgrammingError


DEFAULT_ADMIN_USERNAME = "aaryaholidays"


def ensure_admin_superuser():
    user_model = get_user_model()

    try:
        existing_user = user_model.objects.filter(username=DEFAULT_ADMIN_USERNAME).first()
        if existing_user:
            return existing_user

        admin_username = os.environ.get("BOOTSTRAP_ADMIN_USERNAME", DEFAULT_ADMIN_USERNAME)
        admin_password = os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "").strip()
        if not admin_password:
            return None

        return user_model.objects.create_superuser(
            username=admin_username,
            password=admin_password,
            email="",
        )
    except (OperationalError, ProgrammingError):
        return None