"""FRREP-AC002/AC007/VL003 — version history + per-version downloads must be
gated by the parent document's visibility and watermarked, not served from the
raw media URL.

Regression: previously ``VersionListView`` was ``LoginRequiredMixin`` only and
``version_history.html`` linked ``{{ v.file.url }}`` directly, so any logged-in
user could list and download historical versions of a Restricted/Internal
document, unwatermarked.
"""

from __future__ import annotations

import itertools

import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client
from django.urls import reverse

from apps.repository.documents.models import Document, DocumentVersion

PDF_BYTES = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n1 0 obj<</Type/Catalog>>endobj\ntrailer<<>>\n%%EOF\n"
_seq = itertools.count(1)


def _doc_with_version(collection, owner, *, visibility):
    doc = Document.objects.create(
        title="Confidential field report",
        abstract="Body.",
        collection=collection,
        document_type=Document.DocumentType.TECHNICAL_REPORT,
        license_type=Document.License.CC_BY,
        visibility=visibility,
        status=Document.Status.PUBLISHED,
        submitted_by=owner,
        public_document_id=f"VER-{next(_seq):05d}",
        file=SimpleUploadedFile("v2.pdf", PDF_BYTES, content_type="application/pdf"),
    )
    version = DocumentVersion.objects.create(
        document=doc,
        version_number="1.0",
        file=SimpleUploadedFile("v1.pdf", PDF_BYTES, content_type="application/pdf"),
        uploaded_by=owner,
    )
    return doc, version


def _bytes(resp):
    return b"".join(resp.streaming_content) if resp.streaming else resp.content


@pytest.mark.django_db
def test_restricted_version_history_denied_to_random_user(restricted_collection, manager_user, submitter_user):
    doc, _ = _doc_with_version(restricted_collection, manager_user, visibility=Document.Visibility.RESTRICTED)
    client = Client()
    client.force_login(submitter_user)  # authenticated, but not owner/manager
    resp = client.get(reverse("repo_documents:document_versions", kwargs={"uid": doc.document_uid}))
    assert resp.status_code == 403


@pytest.mark.django_db
def test_restricted_version_download_denied_to_random_user(restricted_collection, manager_user, submitter_user):
    doc, version = _doc_with_version(restricted_collection, manager_user, visibility=Document.Visibility.RESTRICTED)
    client = Client()
    client.force_login(submitter_user)
    resp = client.get(
        reverse("repo_documents:document_version_download", kwargs={"uid": doc.document_uid, "pk": version.pk})
    )
    assert resp.status_code == 403


@pytest.mark.django_db
def test_manager_can_view_and_download_restricted_version(restricted_collection, manager_user):
    doc, version = _doc_with_version(restricted_collection, manager_user, visibility=Document.Visibility.RESTRICTED)
    client = Client()
    client.force_login(manager_user)
    hist = client.get(reverse("repo_documents:document_versions", kwargs={"uid": doc.document_uid}))
    assert hist.status_code == 200
    dl = client.get(
        reverse("repo_documents:document_version_download", kwargs={"uid": doc.document_uid, "pk": version.pk})
    )
    assert dl.status_code == 200
    assert _bytes(dl).startswith(b"%PDF")
    assert dl["Content-Disposition"].startswith("attachment;")


@pytest.mark.django_db
def test_public_version_download_available_to_anonymous(public_collection, manager_user):
    doc, version = _doc_with_version(public_collection, manager_user, visibility=Document.Visibility.PUBLIC_OPEN)
    resp = Client().get(
        reverse("repo_documents:document_version_download", kwargs={"uid": doc.document_uid, "pk": version.pk})
    )
    assert resp.status_code == 200
    assert _bytes(resp).startswith(b"%PDF")
