"""Tests for server list target_path_unset filter."""
from unittest.mock import AsyncMock, MagicMock, patch

import bcrypt
import pytest
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from server.application.services.auth_service import AuthService
from server.domain.models import Admin, Base, Server
from server.infrastructure.database.admin_repo import AdminRepositoryImpl
from server.infrastructure.database.audit_log_repo import AuditLogRepositoryImpl
from server.infrastructure.database.server_repo import ServerRepositoryImpl
from server.utils.posix_paths import is_unset_target_path


@pytest_asyncio.fixture
async def db_session():
    engine = create_async_engine("sqlite+aiosqlite://", echo=False)
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    session_factory = async_sessionmaker(engine, class_=AsyncSession)
    session = session_factory()
    try:
        yield session
    finally:
        await session.close()
        await engine.dispose()


@pytest_asyncio.fixture
async def api_client(db_session):
    from server.api.dependencies import get_db
    from server.main import app

    async def override_get_session():
        yield db_session

    app.dependency_overrides[get_db] = override_get_session
    transport = ASGITransport(app=app)
    client = AsyncClient(transport=transport, base_url="http://test")
    try:
        yield client
    finally:
        await client.aclose()
        app.dependency_overrides.clear()


@pytest_asyncio.fixture
async def test_admin(db_session):
    password_hash = bcrypt.hashpw(b"test123", bcrypt.gensalt()).decode()
    admin = Admin(
        username="testadmin",
        password_hash=password_hash,
        is_active=True,
        totp_enabled=False,
    )
    db_session.add(admin)
    await db_session.commit()
    await db_session.refresh(admin)

    auth_service = AuthService(
        admin_repo=AdminRepositoryImpl(db_session),
        attempt_repo=MagicMock(),
        audit_repo=AuditLogRepositoryImpl(db_session),
    )
    token = auth_service._create_access_token(admin)
    return {"admin": admin, "token": token}


@pytest.mark.parametrize(
    "raw,expected",
    [
        (None, True),
        ("", True),
        ("  ", True),
        ("/www/wwwroot", True),
        ("  /www/wwwroot  ", True),
        ("/www/wwwroot/", False),
        ("/www/wwwroot/site", False),
        ("/var/www/html", False),
    ],
)
def test_is_unset_target_path(raw, expected):
    assert is_unset_target_path(raw) is expected


async def _seed_servers(db_session):
    rows = [
        Server(name="empty-path", domain="1.1.1.1", target_path=None),
        Server(name="default-path", domain="2.2.2.2", target_path="/www/wwwroot"),
        Server(name="custom-path", domain="3.3.3.3", target_path="/www/wwwroot/site"),
        Server(name="trailing-slash", domain="4.4.4.4", target_path="/www/wwwroot/"),
        Server(name="中-养号", domain="5.5.5.5", target_path=None, category="yanghao"),
    ]
    for row in rows:
        db_session.add(row)
    await db_session.commit()
    return rows


@pytest.mark.asyncio
async def test_repo_filter_unset_true(db_session):
    await _seed_servers(db_session)
    repo = ServerRepositoryImpl(db_session)
    servers, total = await repo.get_paginated(target_path_unset=True, limit=50)
    names = {s.name for s in servers}
    assert total == 3
    assert names == {"empty-path", "default-path", "中-养号"}


@pytest.mark.asyncio
async def test_repo_filter_unset_false(db_session):
    await _seed_servers(db_session)
    repo = ServerRepositoryImpl(db_session)
    servers, total = await repo.get_paginated(target_path_unset=False, limit=50)
    names = {s.name for s in servers}
    assert total == 2
    assert names == {"custom-path", "trailing-slash"}


@pytest.mark.asyncio
async def test_repo_filter_with_search(db_session):
    await _seed_servers(db_session)
    repo = ServerRepositoryImpl(db_session)
    servers, total = await repo.get_paginated(
        search="default", target_path_unset=True, limit=50,
    )
    assert total == 1
    assert servers[0].name == "default-path"


@pytest.mark.asyncio
async def test_api_target_path_unset(api_client, test_admin, db_session):
    await _seed_servers(db_session)
    headers = {"Authorization": f"Bearer {test_admin['token']}"}
    admin = test_admin["admin"]

    async def fake_verify(token, request):
        return admin if token == test_admin["token"] else None

    with patch("server.api.auth_jwt._verify_token", side_effect=fake_verify), patch(
        "server.api.servers.get_redis",
    ) as mock_redis:
        pipe = AsyncMock()
        pipe.hgetall = MagicMock(return_value=pipe)
        pipe.execute = AsyncMock(return_value=[{}] * 5)
        mock_redis.return_value.pipeline = MagicMock(return_value=pipe)

        unset = await api_client.get(
            "/api/servers/?target_path_unset=true&per_page=50",
            headers=headers,
        )
        assert unset.status_code == 200
        unset_names = {i["name"] for i in unset.json()["items"]}
        assert unset_names == {"empty-path", "default-path", "中-养号"}

        configured = await api_client.get(
            "/api/servers/?target_path_unset=false&per_page=50",
            headers=headers,
        )
        configured_names = {i["name"] for i in configured.json()["items"]}
        assert configured_names == {"custom-path", "trailing-slash"}

        all_resp = await api_client.get("/api/servers/?per_page=50", headers=headers)
        assert all_resp.json()["total"] == 5

        by_name = await api_client.get(
            "/api/servers/?search=empty-path&per_page=50",
            headers=headers,
        )
        assert by_name.status_code == 200
        assert by_name.json()["total"] == 1
        assert by_name.json()["items"][0]["name"] == "empty-path"

        excluded = await api_client.get(
            "/api/servers/?search=empty-path&target_path_unset=false&per_page=50",
            headers=headers,
        )
        assert excluded.json()["total"] == 0

        cn = await api_client.get(
            "/api/servers/?search=养号&per_page=50",
            headers=headers,
        )
        assert cn.json()["total"] == 1
        assert cn.json()["items"][0]["name"] == "中-养号"

        wrong_cat = await api_client.get(
            "/api/servers/?search=养号&category=other&per_page=50",
            headers=headers,
        )
        assert wrong_cat.json()["total"] == 0
