"""Document matching. The wrong file reaching a customer is worse than no file,
so these lock down what download_link is allowed to guess at."""
from unittest.mock import patch

import pytest

from app.services.content import documents as documents


def _docs(*names):
    return [{"source_id": f"sid-{i}", "file_name": n, "category": "Brand",
             "uploaded_at": None} for i, n in enumerate(names)]


def _install(monkeypatch, *names):
    monkeypatch.setattr(documents, "list_documents", lambda t, c=None: _docs(*names))
    monkeypatch.setattr(documents.storage_service, "download_url",
                        lambda tenant, blob, hours=24: f"https://blob/{blob}")


@pytest.fixture
def stored(monkeypatch):
    """Patch the listing and give every found file a working storage link."""
    return lambda *names: _install(monkeypatch, *names)


def test_exact_name_wins(stored):
    stored("pricing.pdf", "pricing-enterprise.pdf")
    assert documents.download_link("org_x", "pricing.pdf")["file_name"] == "pricing.pdf"


def test_partial_name_resolves_when_unambiguous(stored):
    stored("reseller-pricing-2026.pdf", "warranty.pdf")
    got = documents.download_link("org_x", "reseller-pricing")
    assert got["file_name"] == "reseller-pricing-2026.pdf"


def test_short_stored_name_never_swallows_a_longer_request(stored):
    """'e.pdf' is a substring of 'brochure.pdf'. It must not answer for it."""
    stored("e.pdf", "brochure-2026.pdf")
    assert documents.download_link("org_x", "brochure.pdf") == {}
    assert documents.download_link("org_x", "price.pdf") == {}


def test_ambiguous_partial_returns_nothing(stored):
    """Two files could match; guessing one would look authoritative and be wrong."""
    stored("pricing-standard.pdf", "pricing-enterprise.pdf")
    assert documents.download_link("org_x", "pricing") == {}


def test_unknown_and_empty_names_return_nothing(stored):
    stored("brochure.pdf")
    assert documents.download_link("org_x", "does-not-exist.pdf") == {}
    assert documents.download_link("org_x", "") == {}


def test_link_points_at_this_service_not_storage(stored):
    """The URL a visitor is given must never expire and must not leak the
    storage account, so it addresses our own download endpoint."""
    stored("warranty.pdf")
    got = documents.download_link("org_x", "warranty.pdf")
    assert "/documents/download" in got["url"]
    assert "blob.core.windows.net" not in got["url"]
    assert "sig=" not in got["url"]
    assert "source_id=sid-0" in got["url"] and "tenant_id=org_x" in got["url"]
    assert got["category"] == "Brand"


def test_storage_link_is_minted_on_demand(stored):
    """blob_url is what the download endpoint redirects to, generated per click."""
    stored("warranty.pdf")
    document = documents.find_document("org_x", "sid-0")
    assert document["file_name"] == "warranty.pdf"
    assert documents.blob_url("org_x", document) == "https://blob/sid-0_warranty.pdf"


def test_missing_blob_yields_no_storage_link(monkeypatch):
    """Metadata can outlive the stored file; never redirect to a dead link."""
    monkeypatch.setattr(documents, "list_documents", lambda t, c=None: _docs("gone.pdf"))
    monkeypatch.setattr(documents.storage_service, "download_url",
                        lambda tenant, blob, hours=24: "")
    assert documents.blob_url("org_x", documents.find_document("org_x", "sid-0")) == ""


def test_unknown_document_id_finds_nothing(stored):
    stored("warranty.pdf")
    assert documents.find_document("org_x", "sid-does-not-exist") == {}
    assert documents.find_document("org_x", "") == {}
    assert documents.blob_url("org_x", {}) == ""
