import io
import os
import tempfile

import pytest
from django.test import Client
from rest_framework.test import APIClient


@pytest.fixture
def client():
    return Client()


@pytest.fixture
def api_client():
    return APIClient()


@pytest.fixture
def png_file():
    """Minimal valid 1×1 PNG."""
    data = (
        b"\x89PNG\r\n\x1a\n"  # signature
        b"\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
        b"\x08\x02\x00\x00\x00\x90wS\xde"  # 1x1 RGB
        b"\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8N"
        b"\x00\x00\x00\x00IEND\xaeB`\x82"
    )
    return io.BytesIO(data)


@pytest.fixture
def pdf_file():
    """Minimal valid PDF."""
    data = (
        b"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n"
        b"2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n"
        b"3 0 obj<</Type/Page/MediaBox[0 0 612 792]/Parent 2 0 R>>endobj\n"
        b"xref\n0 4\ntrailer<</Size 4/Root 1 0 R>>\nstartxref\n0\n%%EOF"
    )
    return io.BytesIO(data)


@pytest.fixture(autouse=True)
def use_tmp_upload_dir(settings, tmp_path):
    """Redirect FILE_UPLOADS_FOLDER to a temp dir for each test."""
    settings.FILE_UPLOADS_FOLDER = str(tmp_path)
    yield


@pytest.fixture(autouse=True)
def use_locmem_cache(settings):
    """Override Redis cache with in-process LocMemCache so tests don't need a Redis server."""
    settings.CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        }
    }
    yield
