"""
Pytest configuration for platform tests.
"""
import os
import sys
import pytest

# Add backend to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.test')

import django
django.setup()

from django.conf import settings


@pytest.fixture(scope='session')
def django_db_setup():
    """Use existing database for tests."""
    pass


@pytest.fixture(scope='session')
def django_db_modify_db_settings():
    """Modify database settings to reuse existing database."""
    pass


@pytest.fixture
def api_client():
    """Create a test API client with proper tenant host."""
    from rest_framework.test import APIClient
    client = APIClient()
    # Set default host for tenant middleware
    client.defaults['HTTP_HOST'] = 'localhost'
    client.defaults['SERVER_NAME'] = 'localhost'
    return client


@pytest.fixture
def create_user(db):
    """Factory fixture to create users."""
    from apps.core.auth.models import User
    
    def _create_user(
        email='test@example.com',
        password='testpass123',
        first_name='Test',
        last_name='User',
        is_active=True,
        is_staff=False,
        is_superuser=False,
    ):
        user = User.objects.create_user(
            email=email,
            password=password,
            first_name=first_name,
            last_name=last_name,
            is_active=is_active,
            is_staff=is_staff,
            is_superuser=is_superuser,
        )
        return user
    
    return _create_user


@pytest.fixture
def authenticated_client(api_client, create_user):
    """Create an authenticated API client."""
    user = create_user()
    api_client.force_authenticate(user=user)
    return api_client, user


@pytest.fixture
def admin_client(api_client, create_user):
    """Create an authenticated admin API client."""
    user = create_user(
        email='admin@example.com',
        is_staff=True,
        is_superuser=True,
    )
    api_client.force_authenticate(user=user)
    return api_client, user
