import pytest

from smoothschedule.identity.users.models import User
from smoothschedule.identity.users.tests.factories import UserFactory


@pytest.fixture(autouse=True)
def _media_storage(settings, tmpdir) -> None:
    settings.MEDIA_ROOT = tmpdir.strpath


@pytest.fixture
def user(db) -> User:
    """
    Fixture for creating a real User instance in the database.

    Use this only for integration tests that require actual database access.
    For unit tests, use create_mock_user() from factories.py instead.
    """
    return UserFactory()


# =============================================================================
# Shared Tenant Fixtures (Session-scoped for performance)
# =============================================================================
# Creating a tenant in django-tenants runs all migrations (~40 seconds).
# These fixtures are session-scoped to avoid recreating tenants for each test.

_shared_tenant_cache = {}


@pytest.fixture(scope="session")
def shared_tenant(django_db_setup, django_db_blocker):
    """
    Session-scoped tenant fixture for tests that need a real tenant.

    This tenant is created ONCE per test session and reused across all tests.
    Use this instead of creating tenants in individual tests to avoid the
    ~40 second migration overhead per tenant.

    Usage:
        @pytest.mark.django_db
        def test_something(shared_tenant):
            user = User(tenant=shared_tenant, ...)
    """
    from smoothschedule.identity.core.models import Tenant

    with django_db_blocker.unblock():
        # Check if tenant already exists from a previous run (--reuse-db)
        tenant = Tenant.objects.filter(schema_name="sharedtest").first()
        if not tenant:
            tenant = Tenant.objects.create(
                name="Shared Test Business",
                schema_name="sharedtest"
            )
        return tenant


@pytest.fixture(scope="session")
def second_shared_tenant(django_db_setup, django_db_blocker):
    """
    Second session-scoped tenant for tests that need multiple tenants.
    """
    from smoothschedule.identity.core.models import Tenant

    with django_db_blocker.unblock():
        tenant = Tenant.objects.filter(schema_name="sharedtest2").first()
        if not tenant:
            tenant = Tenant.objects.create(
                name="Shared Test Business 2",
                schema_name="sharedtest2"
            )
        return tenant
