import tempfile
from pathlib import Path

from fastapi.testclient import TestClient

from media_library_viewer_api.main import app
from media_library_viewer_api.services.settings_store import SettingsStore


def test_dashboard_backups():
    with tempfile.TemporaryDirectory() as tmpdir:
        db_path = Path(tmpdir) / "test_settings.sqlite"
        store = SettingsStore(db_path)
        store.init_schema()

        # Monkey-patch the global store for this test
        import media_library_viewer_api.auth as auth_module
        from media_library_viewer_api.services import settings_store

        original_store = settings_store._store
        settings_store._store = store
        auth_module._API_KEY = None

        try:
            client = TestClient(app)
            response = client.get("/api/dashboard/backups")
            assert response.status_code == 200
            data = response.json()
            assert "total_jobs" in data
            assert "success_rate_24h" in data
        finally:
            settings_store._store = original_store
            auth_module._API_KEY = None


def test_post_backup_report():
    with tempfile.TemporaryDirectory() as tmpdir:
        db_path = Path(tmpdir) / "test_settings.sqlite"
        store = SettingsStore(db_path)
        store.init_schema()

        # Monkey-patch the global store for this test
        import media_library_viewer_api.auth as auth_module
        from media_library_viewer_api.auth import get_api_key
        from media_library_viewer_api.services import settings_store

        original_store = settings_store._store
        settings_store._store = store
        auth_module._API_KEY = None

        try:
            client = TestClient(app)
            api_key = get_api_key()

            response = client.post(
                "/api/backups/report",
                headers={"Authorization": f"Bearer {api_key}"},
                json={
                    "name": "test-backup",
                    "started_at": "2026-05-11T02:00:00Z",
                    "status": "success",
                    "ended_at": "2026-05-11T02:15:00Z",
                    "duration_ms": 900000,
                    "bytes_transferred": 1024,
                },
            )
            assert response.status_code == 200
            data = response.json()
            assert data["status"] == "success"
        finally:
            settings_store._store = original_store
            auth_module._API_KEY = None
