"""GET/PUT /api/admin/platform-media-storage — Auth-Matrix (kein Live-DB nötig)."""
from __future__ import annotations

import os
from unittest.mock import MagicMock, patch

import pytest
from fastapi.testclient import TestClient

os.environ.setdefault("SKIP_DB_MIGRATE", "1")

from auth import require_auth
from main import app


@pytest.fixture
def client() -> TestClient:
    return TestClient(app)


@pytest.fixture(autouse=True)
def _clear_overrides():
    yield
    app.dependency_overrides.pop(require_auth, None)


def test_platform_media_storage_get_requires_platform_admin(client: TestClient) -> None:
    def _trainer():
        return {"profile_id": 1, "role": "trainer"}

    app.dependency_overrides[require_auth] = _trainer
    r = client.get("/api/admin/platform-media-storage", headers={"X-Auth-Token": "t"})
    assert r.status_code == 403


def test_platform_media_storage_put_requires_superadmin(client: TestClient) -> None:
    def _admin():
        return {"profile_id": 1, "role": "admin"}

    app.dependency_overrides[require_auth] = _admin
    r = client.put(
        "/api/admin/platform-media-storage",
        headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
        json={"local_relative_root": "foo"},
    )
    assert r.status_code == 403


@patch("routers.platform_media_storage.get_effective_media_root", return_value=__import__("pathlib").Path("/tmp/media"))
def test_platform_media_storage_get_ok_for_admin(mock_root, client: TestClient) -> None:
    def _admin():
        return {"profile_id": 1, "role": "admin"}

    app.dependency_overrides[require_auth] = _admin

    mock_cm = MagicMock()
    mock_conn = MagicMock()
    mock_cm.__enter__.return_value = mock_conn
    mock_cm.__exit__.return_value = False
    mock_cur = MagicMock()
    mock_cur.fetchone.return_value = {
        "storage_backend": "local",
        "local_relative_root": "nas",
    }

    with patch("routers.platform_media_storage.get_db", return_value=mock_cm), patch(
        "routers.platform_media_storage.get_cursor", return_value=mock_cur
    ):
        r = client.get("/api/admin/platform-media-storage", headers={"X-Auth-Token": "t"})

    assert r.status_code == 200
    body = r.json()
    assert body["storage_backend"] == "local"
    assert body["local_relative_root"] == "nas"
