"""
File Service — Test Fixtures.
"""
import uuid

import pytest
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework.test import APIClient

from apps.core.tenant.models import Tenant, Domain

User = get_user_model()
from apps.services.file_service.models import (
    FileReference,
    FileStatus,
    ReferenceContext,
    StoredFile,
    StorageBackend,
)


@pytest.fixture
def tenant(db):
    """Tenant عمومی تست."""
    tenant, _ = Tenant.objects.get_or_create(
        schema_name='public',
        defaults={'name': 'تست'},
    )
    Domain.objects.get_or_create(
        domain='localhost',
        defaults={'tenant': tenant, 'is_primary': True},
    )
    return tenant


@pytest.fixture
def user(tenant, db):
    """کاربر اصلی تست."""
    return User.objects.create_user(
        email=f'filetest-{uuid.uuid4().hex[:6]}@test.com',
        password='testpass123',
        first_name='علی',
        last_name='محمدی',
        tenant=tenant,
    )


@pytest.fixture
def api_client():
    """کلاینت بدون احراز هویت."""
    return APIClient()


@pytest.fixture
def authenticated_client(user):
    """کلاینت با احراز هویت."""
    client = APIClient()
    client.force_authenticate(user=user)
    return client


@pytest.fixture
def sample_file():
    """فایل نمونه برای آپلود."""
    return SimpleUploadedFile(
        name='test-file.txt',
        content=b'Hello Nexa File Service Test Content!',
        content_type='text/plain',
    )


@pytest.fixture
def sample_image():
    """فایل تصویر نمونه."""
    return SimpleUploadedFile(
        name='test-image.png',
        content=b'\x89PNG\r\n\x1a\n' + b'\x00' * 100,
        content_type='image/png',
    )


@pytest.fixture
def stored_file(tenant, user, db):
    """فایل ذخیره‌شده آزمایشی."""
    return StoredFile.objects.create(
        tenant=tenant,
        original_name='test-doc.pdf',
        mime_type='application/pdf',
        size=1024,
        extension='pdf',
        storage_backend=StorageBackend.LOCAL,
        storage_path=f'files/{tenant.id}/2025/01/{uuid.uuid4()}.pdf',
        checksum='a' * 64,
        status=FileStatus.ACTIVE,
        uploaded_by=user,
    )


@pytest.fixture
def file_reference(tenant, user, stored_file, db):
    """ارجاع فایل آزمایشی."""
    return FileReference.objects.create(
        tenant=tenant,
        stored_file=stored_file,
        context=ReferenceContext.CHAT,
        context_id=uuid.uuid4(),
        display_name='فایل تست',
        created_by=user,
        is_active=True,
    )
