"""Unit tests for files browse ETag helpers."""

from server.application.services.files_browse_service import (
    browse_cache_key,
    compute_browse_etag,
    get_cached_browse,
    invalidate_browse_cache,
    invalidate_browse_parents,
    set_cached_browse,
)


def test_compute_browse_etag_stable():
    items = [
        {"name": "b.txt", "modified": "2026-01-01", "size": 10},
        {"name": "a.dir", "modified": "2026-01-02", "size": 0},
    ]
    e1 = compute_browse_etag("/var/www", items)
    e2 = compute_browse_etag("/var/www", list(reversed(items)))
    assert e1 == e2
    assert e1.startswith('W/"')
    assert len(e1) > 10


def test_compute_browse_etag_changes_when_permissions_change():
    base = [{"name": "a.txt", "modified": "2026-01-01", "size": 10, "permissions": "-rw-r--r--", "owner": "www", "group": "www", "mode_octal": "644"}]
    changed = [{**base[0], "permissions": "-rwxr-xr-x", "mode_octal": "755"}]
    assert compute_browse_etag("/var/www", base) != compute_browse_etag("/var/www", changed)


def test_browse_server_cache_304_path():
    payload = {"path": "/tmp", "items": [{"name": "x", "modified": "t", "size": 1}]}
    etag = compute_browse_etag("/tmp", payload["items"])
    set_cached_browse(1, "/tmp", etag, payload)
    hit = get_cached_browse(1, "/tmp")
    assert hit is not None
    assert hit[0] == etag
    assert hit[1]["items"][0]["name"] == "x"
    invalidate_browse_cache(1, "/tmp")
    assert get_cached_browse(1, "/tmp") is None
    assert browse_cache_key(1, "/tmp") == "1:/tmp"


def test_invalidate_browse_parents_dedupes():
    payload = {"path": "/var/www", "items": []}
    etag = compute_browse_etag("/var/www", [])
    set_cached_browse(2, "/var/www", etag, payload)
    invalidate_browse_parents(2, "/var/www/a.txt", "/var/www/b.txt")
    assert get_cached_browse(2, "/var/www") is None
