"""Public media-serving layer tests -- Storage Path Layer / Phase 2.

Covers blueprints/media/media.py (offer photo/video + agent avatar
serving) and the CRM-authenticated document download route added to
InvestmentManager/routes/offer_catalog.py, in BOTH legacy and external
DATA_DIR mode. Isolation: monkeypatch.setenv("DATA_DIR", ...) only -- never
chdir().
"""
import io

from tests.storage.conftest import login_as_crm_user


class TestPublicOfferImageAccess:
    def test_legacy_mode_serves_offer_image(self, client, isolated_storage_root):
        offer_dir = isolated_storage_root / "static" / "images" / "301"
        offer_dir.mkdir(parents=True)
        (offer_dir / "image_301_url_0.jpg").write_bytes(b"legacy-photo-bytes")

        resp = client.get("/static/images/301/image_301_url_0.jpg")
        assert resp.status_code == 200
        assert resp.data == b"legacy-photo-bytes"

    def test_external_mode_serves_offer_image_from_data_dir(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        offer_dir = tmp_path / "offers" / "302"
        offer_dir.mkdir(parents=True)
        (offer_dir / "image_302_url_0.png").write_bytes(b"external-photo-bytes")

        # Same URL shape as legacy mode -- proves the public URL contract
        # is unchanged even though the file physically lives in DATA_DIR.
        resp = client.get("/static/images/302/image_302_url_0.png")
        assert resp.status_code == 200
        assert resp.data == b"external-photo-bytes"

    def test_external_mode_serves_offer_video(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        offer_dir = tmp_path / "offers" / "303"
        offer_dir.mkdir(parents=True)
        (offer_dir / "video_303.mp4").write_bytes(b"video-bytes")

        resp = client.get("/static/images/303/video_303.mp4")
        assert resp.status_code == 200
        assert resp.data == b"video-bytes"

    def test_external_mode_404s_when_file_absent(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        resp = client.get("/static/images/304/image_304_url_0.jpg")
        assert resp.status_code == 404

    def test_design_assets_still_served_by_flask_static_in_external_mode(self, client, tmp_path, monkeypatch):
        # investment_logo.webp etc. never move to DATA_DIR -- confirm the
        # single-segment /static/images/<file> URL still falls through to
        # Flask's normal static handler even when DATA_DIR is set.
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        resp = client.get("/static/images/investment_logo.webp")
        # 200 if the real asset exists on this machine, 404 if not -- either
        # way it must NOT be handled by the offer-media route (which would
        # 404 unconditionally for a 1-segment path under a different code
        # path). We assert it is Flask's static 404 page shape by checking
        # the route was not intercepted: a 3-segment offer_id/filename
        # never applies here, so this just confirms no 500/crash.
        assert resp.status_code in (200, 404)


class TestPublicAgentAvatarAccess:
    def test_legacy_mode_serves_avatar(self, client, isolated_storage_root):
        images_dir = isolated_storage_root / "static" / "images"
        images_dir.mkdir(parents=True, exist_ok=True)
        (images_dir / "agent_501.jpg").write_bytes(b"legacy-avatar-bytes")

        resp = client.get("/static/images/agent_501.jpg")
        assert resp.status_code == 200
        assert resp.data == b"legacy-avatar-bytes"

    def test_external_mode_serves_avatar_from_dedicated_agents_dir(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        agents_dir = tmp_path / "agents"
        agents_dir.mkdir(parents=True)
        (agents_dir / "agent_502.webp").write_bytes(b"external-avatar-bytes")

        resp = client.get("/static/images/agent_502.webp")
        assert resp.status_code == 200
        assert resp.data == b"external-avatar-bytes"

    def test_external_mode_404s_when_avatar_absent(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        resp = client.get("/static/images/agent_503.jpg")
        assert resp.status_code == 404

    def test_disallowed_extension_rejected(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        agents_dir = tmp_path / "agents"
        agents_dir.mkdir(parents=True)
        (agents_dir / "agent_504.gif").write_bytes(b"x")
        resp = client.get("/static/images/agent_504.gif")
        assert resp.status_code == 404


class TestPrivateDocsInaccessibleAnonymously:
    """Section 9's explicit requirement: 'anonymous request cannot fetch
    offer docs from DATA_DIR'."""

    def test_anonymous_request_cannot_fetch_offer_docs_from_data_dir(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        docs_dir = tmp_path / "offers" / "601" / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "contract.pdf").write_bytes(b"private-contract-bytes")

        # No CRM session at all.
        resp = client.get("/static/images/601/docs/contract.pdf")
        assert resp.status_code == 404
        assert resp.data != b"private-contract-bytes"

    def test_anonymous_request_cannot_fetch_notes_from_data_dir(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        offer_dir = tmp_path / "offers" / "602"
        offer_dir.mkdir(parents=True)
        (offer_dir / "notes.md").write_text("private agent notes")

        resp = client.get("/static/images/602/notes.md")
        assert resp.status_code == 404

    def test_anonymous_request_cannot_fetch_description_from_data_dir(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        offer_dir = tmp_path / "offers" / "603"
        offer_dir.mkdir(parents=True)
        (offer_dir / "description_603.md").write_text("draft description")

        resp = client.get("/static/images/603/description_603.md")
        assert resp.status_code == 404

    def test_crm_authenticated_download_route_works_in_external_mode(self, client, tmp_path, monkeypatch):
        # The replacement, authenticated way to fetch a document.
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        docs_dir = tmp_path / "offers" / "604" / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "contract.pdf").write_bytes(b"contract-bytes")

        login_as_crm_user(client, master=True)
        resp = client.get("/crm/offers/documents/604/file/contract.pdf")
        assert resp.status_code == 200
        assert resp.data == b"contract-bytes"

    def test_crm_authenticated_download_route_rejects_anonymous(self, client, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        docs_dir = tmp_path / "offers" / "605" / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "contract.pdf").write_bytes(b"contract-bytes")

        resp = client.get("/crm/offers/documents/605/file/contract.pdf")
        assert resp.status_code == 403
        assert resp.data != b"contract-bytes"

    def test_crm_authenticated_download_route_works_in_legacy_mode_too(self, client, isolated_storage_root):
        docs_dir = isolated_storage_root / "static" / "images" / "606" / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "umowa.pdf").write_bytes(b"legacy-contract-bytes")

        login_as_crm_user(client, master=True)
        resp = client.get("/crm/offers/documents/606/file/umowa.pdf")
        assert resp.status_code == 200
        assert resp.data == b"legacy-contract-bytes"
