"""Refresh token when admin.token_version is NULL (legacy cookie contains ':None')."""

from unittest.mock import AsyncMock, MagicMock

import pytest

from server.application.services.auth_service import (
    AuthService,
    _admin_token_version,
    _parse_refresh_token_version,
)
from server.domain.models import Admin


def test_admin_token_version_null_is_zero():
    admin = Admin(id=1, username="a", password_hash="x", token_version=None)
    assert _admin_token_version(admin) == 0


def test_parse_refresh_token_version_accepts_none_literal():
    assert _parse_refresh_token_version("None") == 0
    assert _parse_refresh_token_version("0") == 0


@pytest.mark.asyncio
async def test_refresh_succeeds_with_legacy_none_version_cookie(monkeypatch):
    admin = Admin(id=1, username="admin", password_hash="x", is_active=True, token_version=None)
    service = AuthService(AsyncMock(), AsyncMock(), AsyncMock())
    service.admin_repo.get_by_id = AsyncMock(return_value=admin)
    service._audit = AsyncMock()
    service._create_access_token = MagicMock(return_value="access")
    service._create_refresh_token = MagicMock(return_value="new:1:0")
    service._rotate_refresh_token = AsyncMock(return_value=True)

    token = "legacysecret:1:None"

    async def membership(_admin_id, _token):
        return True

    monkeypatch.setattr(service, "_refresh_token_membership", membership)

    result = await service.refresh_token(token, ip_address="127.0.0.1")

    assert result["success"] is True
    assert result["access_token"] == "access"


def test_create_refresh_token_uses_zero_not_none_string():
    admin = Admin(id=1, username="admin", password_hash="x", token_version=None)
    service = AuthService(AsyncMock(), AsyncMock(), AsyncMock())
    raw = service._create_refresh_token(admin)
    assert raw.endswith(":1:0")
    assert "None" not in raw
