"""Upload-format gate (#2, FRREP-DCI005).

The repository is a document archive, not a media library: audio/video files
must be rejected on **both** the direct-upload path
(`_validate_repository_upload`) and the chunked/resumable path
(`start_resumable_upload`). Document/data/image/archive formats stay allowed.
"""
from __future__ import annotations

import pytest
from django.core.exceptions import ValidationError as DjValidationError
from django.core.files.base import ContentFile

from apps.repository.documents import services


# ── direct upload path ───────────────────────────────────────────────────────


@pytest.mark.parametrize("name", ["clip.mp4", "podcast.mp3", "recording.wav", "movie.mov"])
@pytest.mark.django_db
def test_direct_upload_rejects_audio_video(name):
    f = ContentFile(b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 64, name=name)
    with pytest.raises(DjValidationError) as exc:
        services._validate_repository_upload(f)
    # The message should help the user by naming what IS accepted.
    assert "Allowed" in str(exc.value) or "allowed" in str(exc.value)


@pytest.mark.django_db
def test_direct_upload_accepts_pdf(sample_pdf):
    # Valid PDF magic bytes — should pass every validator (category, size, magic).
    services._validate_repository_upload(sample_pdf)


# ── resumable / chunked path ─────────────────────────────────────────────────


@pytest.mark.parametrize("name", ["clip.mp4", "podcast.mp3", "lecture.mkv"])
@pytest.mark.django_db
def test_resumable_start_rejects_audio_video(submitter_user, name):
    with pytest.raises(DjValidationError):
        services.start_resumable_upload(
            user=submitter_user, filename=name, total_bytes=4096,
        )


@pytest.mark.parametrize(
    "name", ["thesis.pdf", "report.docx", "dataset.xlsx", "figure.jpg", "chart.png", "bundle.zip"]
)
@pytest.mark.django_db
def test_resumable_start_accepts_documents_data_images_archives(submitter_user, name):
    upload = services.start_resumable_upload(
        user=submitter_user, filename=name, total_bytes=4096,
    )
    assert upload.token
    assert upload.status == upload.Status.IN_PROGRESS
