"""FRREP-SR004 — the Search page exposes real type/collection/language filters.

Before this fix, search.html only had an author text filter even though
`search_documents()` already supported document_type/collection/language
(and more). These tests lock in that the filter controls are rendered and
that picking one actually narrows results via the real view.
"""
from __future__ import annotations

import itertools

import pytest
from django.urls import reverse

from apps.repository.documents.models import Document

_seq = itertools.count(1)


def _published(collection, title, **kwargs):
    return Document.objects.create(
        title=title,
        collection=collection,
        status=Document.Status.PUBLISHED,
        visibility=Document.Visibility.PUBLIC_OPEN,
        public_document_id=f"FLT-{next(_seq):05d}",
        **kwargs,
    )


@pytest.mark.django_db
def test_search_page_renders_type_collection_language_filters(public_collection):
    from django.test import Client

    resp = Client().get(reverse("repo_search:search"))
    assert resp.status_code == 200
    body = resp.content.decode()
    assert 'name="type"' in body
    assert 'name="collection"' in body
    assert 'name="language"' in body
    # Options are populated from the real vocab/collection set, not empty.
    assert public_collection.name in body


@pytest.mark.django_db
def test_search_filters_by_document_type(public_collection):
    from django.test import Client

    match = _published(public_collection, "A dataset", document_type=Document.DocumentType.DATASET)
    _published(public_collection, "A report", document_type=Document.DocumentType.TECHNICAL_REPORT)

    resp = Client().get(
        reverse("repo_search:search") + f"?type={Document.DocumentType.DATASET}"
    )
    assert resp.status_code == 200
    assert list(resp.context["object_list"]) == [match]


@pytest.mark.django_db
def test_search_filters_by_language(public_collection):
    from django.test import Client

    match = _published(public_collection, "Etude francophone", language="fr")
    _published(public_collection, "English study", language="en")

    resp = Client().get(reverse("repo_search:search") + "?language=fr")
    assert resp.status_code == 200
    assert list(resp.context["object_list"]) == [match]
