"""Filesystem contract tests for offer notes.md, description_<id>.md
(read-side; see note below on the write-side), and documents/*
(InvestmentManager/routes/offer_catalog.py::handle_notes, handle_documents,
delete_document, _read_offer_description_text).

Scope note on description_<id>.md: the WRITE side only happens inside
add_offer(), which also performs live INSERTs into the estatedata/
localization tables of IDB.db. Exercising that safely would require
seeding a matching minimal schema in an isolated DB purely to reach two
lines of file-writing code already structurally identical to the notes.md
write tested directly below (os.makedirs + open().write()). Given that
tradeoff, only the READ side is covered here (via _read_offer_description_text,
matching modules/investment/functions.py::get_estate_description already
covered in test_offer_images_read_contract.py) -- documented as a coverage
gap in the final report rather than silently skipped.
"""
import io

from tests.storage.conftest import login_as_crm_user


def _offer_dir(tmp_path, offer_id):
    return tmp_path / "static" / "images" / str(offer_id)


class TestOfferNotes:
    def test_get_returns_empty_content_when_no_notes_file(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        resp = client.get("/crm/offers/notes/901")
        assert resp.status_code == 200
        assert resp.get_json() == {"content": ""}

    def test_post_creates_folder_and_writes_notes_md(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        resp = client.post("/crm/offers/notes/902", json={"content": "Ważny klient, zadzwonić jutro."})
        assert resp.status_code == 200
        assert resp.get_json()["success"] is True

        notes_path = _offer_dir(isolated_storage_root, 902) / "notes.md"
        assert notes_path.read_text(encoding="utf-8") == "Ważny klient, zadzwonić jutro."

    def test_post_then_get_round_trips_content(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        client.post("/crm/offers/notes/903", json={"content": "Pierwsza wersja"})
        client.post("/crm/offers/notes/903", json={"content": "Nadpisana wersja"})
        resp = client.get("/crm/offers/notes/903")
        assert resp.get_json()["content"] == "Nadpisana wersja"


class TestOfferDescriptionReadContract:
    def test_read_returns_empty_string_when_missing(self, isolated_storage_root, app):
        from InvestmentManager.routes.offer_catalog import _read_offer_description_text

        with app.test_request_context("/"):
            assert _read_offer_description_text(904) == ""

    def test_read_returns_stripped_file_content(self, isolated_storage_root, app):
        offer_dir = _offer_dir(isolated_storage_root, 905)
        offer_dir.mkdir(parents=True)
        (offer_dir / "description_905.md").write_text("  Opis oferty z opisem.  \n", encoding="utf-8")

        from InvestmentManager.routes.offer_catalog import _read_offer_description_text

        with app.test_request_context("/"):
            assert _read_offer_description_text(905) == "Opis oferty z opisem."


class TestOfferDocuments:
    def test_get_empty_list_when_no_docs_folder_yet(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        resp = client.get("/crm/offers/documents/1001")
        assert resp.status_code == 200
        assert resp.get_json() == {"documents": []}
        # GET itself creates the (empty) docs/ folder -- handle_documents()
        # always calls os.makedirs(docs_path, exist_ok=True) up front.
        assert (_offer_dir(isolated_storage_root, 1001) / "docs").is_dir()

    def test_upload_document(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        resp = client.post(
            "/crm/offers/documents/1002",
            data={"file": (__import__("io").BytesIO(b"pdf-bytes"), "umowa.pdf")},
            content_type="multipart/form-data",
        )
        assert resp.status_code == 200
        body = resp.get_json()
        assert body["success"] is True
        assert body["overwritten"] is False

        doc_path = _offer_dir(isolated_storage_root, 1002) / "docs" / "umowa.pdf"
        assert doc_path.read_bytes() == b"pdf-bytes"

    def test_upload_lists_in_get(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        client.post(
            "/crm/offers/documents/1003",
            data={"file": (__import__("io").BytesIO(b"x"), "aneks.pdf")},
            content_type="multipart/form-data",
        )
        resp = client.get("/crm/offers/documents/1003")
        assert resp.get_json() == {"documents": ["aneks.pdf"]}

    def test_upload_existing_filename_without_force_reports_conflict_and_does_not_overwrite(
        self, client, isolated_storage_root
    ):
        login_as_crm_user(client, master=True)
        docs_dir = _offer_dir(isolated_storage_root, 1004) / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "umowa.pdf").write_bytes(b"original")

        resp = client.post(
            "/crm/offers/documents/1004",
            data={"file": (__import__("io").BytesIO(b"replacement"), "umowa.pdf")},
            content_type="multipart/form-data",
        )
        assert resp.status_code == 200
        assert resp.get_json() == {"exists": True, "filename": "umowa.pdf"}
        assert (docs_dir / "umowa.pdf").read_bytes() == b"original"

    def test_upload_existing_filename_with_force_true_overwrites(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        docs_dir = _offer_dir(isolated_storage_root, 1005) / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "umowa.pdf").write_bytes(b"original")

        resp = client.post(
            "/crm/offers/documents/1005?force=true",
            data={"file": (__import__("io").BytesIO(b"replacement"), "umowa.pdf")},
            content_type="multipart/form-data",
        )
        assert resp.status_code == 200
        body = resp.get_json()
        assert body["success"] is True
        assert body["overwritten"] is True
        assert (docs_dir / "umowa.pdf").read_bytes() == b"replacement"

    def test_delete_document(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        docs_dir = _offer_dir(isolated_storage_root, 1006) / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "do_usuniecia.pdf").write_bytes(b"x")

        resp = client.post(
            "/crm/offers/documents/1006/delete",
            json={"filename": "do_usuniecia.pdf"},
        )
        assert resp.status_code == 200
        assert resp.get_json()["success"] is True
        assert not (docs_dir / "do_usuniecia.pdf").exists()

    def test_delete_nonexistent_document_returns_404(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        resp = client.post(
            "/crm/offers/documents/1007/delete",
            json={"filename": "brak.pdf"},
        )
        assert resp.status_code == 404


class TestOfferDocumentDownloadWorkflow:
    """Phase 2.1: full upload -> list -> download round trip through the
    CRM-authenticated download_offer_document route that
    offers_documents.js now targets, plus overwrite and path-traversal
    coverage. Legacy mode only here (isolated_storage_root); the
    equivalent external-DATA_DIR + anonymous/authenticated matrix already
    lives in tests/storage/test_media_serving.py."""

    def test_upload_then_download_round_trip(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        client.post(
            "/crm/offers/documents/1101",
            data={"file": (io.BytesIO(b"contract-bytes"), "umowa.pdf")},
            content_type="multipart/form-data",
        )
        listed = client.get("/crm/offers/documents/1101").get_json()
        assert listed == {"documents": ["umowa.pdf"]}

        resp = client.get(f"/crm/offers/documents/1101/file/{listed['documents'][0]}")
        assert resp.status_code == 200
        assert resp.data == b"contract-bytes"

    def test_download_is_served_inline_not_forced_attachment(self, client, isolated_storage_root):
        # offers_documents.js reuses this same URL for inline preview
        # (iframe/img/text fetch) as well as download -- a forced
        # "attachment" Content-Disposition would break iframe/img preview.
        login_as_crm_user(client, master=True)
        docs_dir = _offer_dir(isolated_storage_root, 1102) / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "podglad.pdf").write_bytes(b"pdf-bytes")

        resp = client.get("/crm/offers/documents/1102/file/podglad.pdf")
        assert resp.status_code == 200
        disposition = resp.headers.get("Content-Disposition", "")
        assert not disposition.lower().startswith("attachment")

    def test_download_missing_file_returns_404(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        resp = client.get("/crm/offers/documents/1103/file/brak.pdf")
        assert resp.status_code == 404

    def test_overwrite_then_download_returns_new_bytes(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        docs_dir = _offer_dir(isolated_storage_root, 1104) / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "umowa.pdf").write_bytes(b"original")

        client.post(
            "/crm/offers/documents/1104?force=true",
            data={"file": (io.BytesIO(b"replacement"), "umowa.pdf")},
            content_type="multipart/form-data",
        )
        resp = client.get("/crm/offers/documents/1104/file/umowa.pdf")
        assert resp.data == b"replacement"

    def test_download_anonymous_is_rejected(self, client, isolated_storage_root):
        docs_dir = _offer_dir(isolated_storage_root, 1105) / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "poufne.pdf").write_bytes(b"poufne-bytes")

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

    def test_old_public_docs_url_still_returns_404_after_frontend_change(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        docs_dir = _offer_dir(isolated_storage_root, 1106) / "docs"
        docs_dir.mkdir(parents=True)
        (docs_dir / "stary_link.pdf").write_bytes(b"x")

        resp = client.get("/static/images/1106/docs/stary_link.pdf")
        assert resp.status_code == 404

    def test_path_traversal_with_encoded_slash_is_blocked(self, client, isolated_storage_root):
        # <string:filename> structurally rejects '/'; a %2f-encoded slash
        # decodes to an extra path segment that simply fails to match this
        # route at all (Werkzeug 404s rather than routing it through with
        # a slash embedded in `filename`).
        login_as_crm_user(client, master=True)
        offer_dir = _offer_dir(isolated_storage_root, 1107)
        offer_dir.mkdir(parents=True)
        (offer_dir / "description_1107.md").write_text("private description")

        resp = client.get("/crm/offers/documents/1107/file/..%2fdescription_1107.md")
        assert resp.status_code == 404

    def test_path_traversal_with_dotdot_segment_is_blocked(self, client, isolated_storage_root):
        login_as_crm_user(client, master=True)
        offer_dir = _offer_dir(isolated_storage_root, 1108)
        offer_dir.mkdir(parents=True)
        (offer_dir / "description_1108.md").write_text("private description")
        (offer_dir / "docs").mkdir()

        # filename=".." resolves docs_path/".." back to offer_dir itself,
        # which is a directory, not a file -- .is_file() correctly rejects it.
        resp = client.get("/crm/offers/documents/1108/file/..")
        assert resp.status_code == 404


class TestOfferDocumentsServedWithoutAuth_SecurityCharacterization:
    """SECURITY CHARACTERIZATION / KNOWN ISSUE -- NOT a contract to keep.

    UPDATE (Storage Path Layer / Phase 2): blueprints/media/media.py now
    registers a route at the exact literal pattern
    /static/images/<int:offer_id>/<path:filename>, which Werkzeug matches
    in preference to Flask's generic /static/<path:filename> catch-all (see
    that module's docstring). That route enforces a strict allow-list
    (offer photos/videos only) BEFORE touching the filesystem, so
    .../docs/<file>, notes.md and description_<id>.md now correctly 404 in
    BOTH legacy and external mode -- a direct, intended side effect of
    building the DATA_DIR-aware media layer (Phase 2 section 9's explicit
    requirement was "external mode must not reproduce this"; getting
    legacy mode fixed too was an unavoidable consequence of one shared,
    consistently-enforced route rather than two different behaviours per
    mode).

    This test now documents the FIXED behaviour instead of the original
    vulnerability. See test_offer_documents_data_dir_security.py for the
    equivalent proof specifically in external DATA_DIR mode.
    """

    def test_document_url_no_longer_publicly_served_even_anonymously(self, app, tmp_path):
        # Even if a file happens to physically exist at the legacy on-disk
        # location the URL implies, the media route's allow-list rejects
        # the request before ever reading it.
        original_static_folder = app.static_folder
        app.static_folder = str(tmp_path)
        try:
            doc_dir = tmp_path / "images" / "9999" / "docs"
            doc_dir.mkdir(parents=True)
            (doc_dir / "confidential_contract.pdf").write_bytes(b"secret-contract-bytes")

            anonymous_client = app.test_client()  # no session_transaction() at all
            resp = anonymous_client.get("/static/images/9999/docs/confidential_contract.pdf")

            assert resp.status_code == 404
        finally:
            app.static_folder = original_static_folder
