"""Phase 0 verification regressions — lock in the 'NOT REPRODUCED' items that
the code already implements correctly (#25, #30, #33).

These guard against silent regressions of features the tester reported as
broken but which were really environment/deploy issues:

- #25  the human Document ID (REPO-YYYY-XXXXXX) renders on the detail page;
- #30  viewing a document writes an AccessEvent; downloading writes a
       DownloadEvent;
- #33  the download view delivers the real file bytes as an attachment.
"""
from __future__ import annotations

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

from apps.repository.analytics.models import AccessEvent, DownloadEvent
from apps.repository.documents.models import Document

PDF_BYTES = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n1 0 obj<</Type/Catalog>>endobj\ntrailer<<>>\n%%EOF\n"


def _published_doc(collection, owner, *, public_id="REPO-2026-ABCDEF"):
    return Document.objects.create(
        title="Maize yield under drought",
        abstract="Body.",
        document_type=Document.DocumentType.THESIS,
        license_type=Document.License.CC_BY,
        language="en",
        year=2026,
        collection=collection,
        visibility=Document.Visibility.PUBLIC_OPEN,
        status=Document.Status.PUBLISHED,
        submitted_by=owner,
        public_document_id=public_id,
        file=SimpleUploadedFile("paper.pdf", PDF_BYTES, content_type="application/pdf"),
    )


# ── #25 — human Document ID on the detail page ───────────────────────────────


@pytest.mark.django_db
def test_public_document_id_renders_on_detail(public_collection, manager_user):
    doc = _published_doc(public_collection, manager_user)
    resp = Client().get(
        reverse("repo_documents:document_detail", kwargs={"uid": doc.document_uid})
    )
    assert resp.status_code == 200
    assert b"REPO-2026-ABCDEF" in resp.content


# ── #30 — view/download analytics events are written ─────────────────────────


@pytest.mark.django_db
def test_viewing_document_records_access_event(public_collection, manager_user):
    doc = _published_doc(public_collection, manager_user)
    Client().get(
        reverse("repo_documents:document_detail", kwargs={"uid": doc.document_uid})
    )
    assert AccessEvent.objects.filter(document=doc).count() == 1


@pytest.mark.django_db
def test_downloading_document_records_download_event(public_collection, manager_user):
    doc = _published_doc(public_collection, manager_user)
    Client().get(
        reverse("repo_documents:document_download", kwargs={"uid": doc.document_uid})
    )
    assert DownloadEvent.objects.filter(document=doc).count() == 1


# ── #33 — the download view delivers a readable file ─────────────────────────


@pytest.mark.django_db
def test_download_view_delivers_file_bytes(public_collection, manager_user):
    doc = _published_doc(public_collection, manager_user)
    resp = Client().get(
        reverse("repo_documents:document_download", kwargs={"uid": doc.document_uid})
    )
    assert resp.status_code == 200
    # Open Access PDF is streamed verbatim (no watermark mangling). The view now
    # uses FileResponse for large-file safety (#33), so read streaming_content.
    body = b"".join(resp.streaming_content) if resp.streaming else resp.content
    assert body == PDF_BYTES
    assert resp["Content-Type"] == "application/pdf"
    assert resp["Content-Disposition"].startswith("attachment;")
    # Storage may append a dedup suffix (paper_<hash>.pdf); the extension is the
    # contract that matters for the browser delivering a readable file.
    assert ".pdf" in resp["Content-Disposition"]
