import httpx
from fastapi.testclient import TestClient

from app.main import app, get_pulp_client

client = TestClient(app)

REPO = {
    "pulp_href": "/pulp/api/v3/repositories/rpm/rpm/abc-123/",
    "name": "rocky9-baseos",
    "latest_version_href": "/pulp/api/v3/repositories/rpm/rpm/abc-123/versions/2/",
    "repo_config": {"gpgcheck": 1, "repo-gpgcheck": 1},
}
VERSION = {
    "pulp_created": "2026-06-01T00:00:00Z",
    "content_summary": {"present": {"rpm.package": {"count": 1500}}},
}


class _FakePulp:
    def __init__(self, repos=None, version=None, fail=False):
        self._repos = repos or []
        self._version = version
        self._fail = fail

    def list_repos(self):
        if self._fail:
            raise httpx.ConnectError("connection refused")
        return self._repos

    def get_version(self, href):
        return self._version


def _use(fake):
    app.dependency_overrides[get_pulp_client] = lambda: fake


def teardown_function():
    app.dependency_overrides.clear()


def test_dashboard_lists_repos():
    _use(_FakePulp(repos=[REPO], version=VERSION))
    resp = client.get("/")
    assert resp.status_code == 200
    body = resp.text
    assert "rocky9-baseos" in body
    assert "v2" in body
    assert "1500" in body
    assert "검증됨" in body  # GPG pass 배지


def test_repos_fragment_standalone():
    _use(_FakePulp(repos=[REPO], version=VERSION))
    resp = client.get("/repos")
    assert resp.status_code == 200
    assert 'id="repo-list"' in resp.text
    assert "rocky9-baseos" in resp.text


def test_dashboard_empty():
    _use(_FakePulp(repos=[]))
    resp = client.get("/")
    assert resp.status_code == 200
    assert "등록된 저장소가 없습니다" in resp.text


def test_dashboard_shows_error_when_pulp_down():
    _use(_FakePulp(fail=True))
    resp = client.get("/")
    assert resp.status_code == 200  # 페이지는 뜨고 에러 메시지를 보여줌
    assert "불러오지 못했습니다" in resp.text
