import sys
import os
from pathlib import Path
from django.conf import settings
from django.core.management import call_command
import django
import pytest

def pytest_configure():
    """
    Configura o Django antes da coleta de testes.
    Isso evita o erro de 'AppRegistryNotReady' durante imports globais.
    """
    base_dir = Path(__file__).resolve().parent
    src_dir = base_dir / "src"
    sys.path.insert(0, str(src_dir))

    if not settings.configured:
        settings.configure(
            DEBUG=True,
            SECRET_KEY='test-secret-key',
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': ':memory:',
                }
            },
            INSTALLED_APPS=[
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.admin',
                'django.contrib.messages',
                'ldap_user',
            ],
            AUTH_USER_MODEL='ldap_user.LdapUser',
            
            MIDDLEWARE=[
                'django.contrib.sessions.middleware.SessionMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'django.contrib.messages.middleware.MessageMiddleware',
            ],
            TEMPLATES=[{
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'APP_DIRS': True,
            }],
        )
        django.setup()
        call_command("migrate", verbosity=0)

@pytest.fixture
def user_model():
    from django.contrib.auth import get_user_model
    return get_user_model()