from pathlib import Path

from backend.app.services.attachment_store import AttachmentStore


def test_store_layout_and_dedup(tmp_path):
    src = tmp_path / "pack.zip"
    src.write_bytes(b"\x00\x01binary\xff")
    store = AttachmentStore(images_root=tmp_path / "images")
    sha = "ab" + "c" * 62

    p1 = store.store(src, sha)
    assert p1.endswith(f"attachments/{sha[:3]}/{sha}.zip")
    assert Path(p1).read_bytes() == b"\x00\x01binary\xff"

    # second store of same sha: returns same path, no rewrite
    before = Path(p1).stat().st_mtime_ns
    p2 = store.store(src, sha)
    assert p2 == p1
    assert Path(p1).stat().st_mtime_ns == before


def test_store_preserves_extension_case_insensitive(tmp_path):
    src = tmp_path / "Doc.PDF"
    src.write_bytes(b"%PDF-1.4")
    store = AttachmentStore(images_root=tmp_path / "images")
    p = store.store(src, "f" * 64)
    assert p.endswith(".pdf")
