"""Shared pytest fixtures for the Repository module."""

from __future__ import annotations

from io import BytesIO

import pytest
from django.contrib.auth import get_user_model
from django.core.files.base import ContentFile

from apps.core.permissions.roles import UserRole

User = get_user_model()


@pytest.fixture
def manager_user(db):
    u = User.objects.create_user(email="repo.manager@test.example", password="pw-test-1234")
    u.role = UserRole.REPO_MANAGER
    u.save()
    return u


@pytest.fixture
def submitter_user(db):
    u = User.objects.create_user(email="submitter@test.example", password="pw-test-1234")
    u.role = UserRole.SCHOLAR
    u.save()
    return u


@pytest.fixture
def public_collection(db, manager_user):
    from apps.repository.documents.models import Collection

    col, _ = Collection.objects.update_or_create(
        slug="theses",
        defaults={
            "name": "Theses",
            "visibility": Collection.Visibility.PUBLIC_OPEN,
            "qa_workflow_enabled": True,
        },
    )
    col.managed_by.add(manager_user)
    return col


@pytest.fixture
def restricted_collection(db, manager_user):
    from apps.repository.documents.models import Collection

    col, _ = Collection.objects.update_or_create(
        slug="reports",
        defaults={
            "name": "Reports",
            "visibility": Collection.Visibility.RESTRICTED,
            "qa_workflow_enabled": True,
        },
    )
    col.managed_by.add(manager_user)
    return col


@pytest.fixture
def sample_pdf():
    # Structurally valid (proper xref/trailer/Root) — not just "starts with
    # %PDF" — so it passes both the magic-bytes gate *and* the FRREP-DCI008
    # structural-corruption probe in `services._validate_file_structure`,
    # which genuinely parses the file rather than sniffing its header.
    from pypdf import PdfWriter

    writer = PdfWriter()
    writer.add_blank_page(width=200, height=200)
    buf = BytesIO()
    writer.write(buf)
    return ContentFile(buf.getvalue(), name="sample.pdf")
