"""JWT 会话存储（Redis db10）。

Refresh token 使用白名单：登录/注册写入 jti，refresh / logout 时校验/删除。
"""
from app.config import settings
from app.redis_client import k, redis_client

REFRESH_TTL = settings.REFRESH_TOKEN_EXPIRE_DAYS * 24 * 3600


def _refresh_key(user_id: int | str, jti: str) -> str:
    return k("refresh", str(user_id), jti)


async def add_refresh(user_id: int | str, jti: str) -> None:
    await redis_client.set(_refresh_key(user_id, jti), "1", ex=REFRESH_TTL)


async def exists_refresh(user_id: int | str, jti: str) -> bool:
    return await redis_client.exists(_refresh_key(user_id, jti)) > 0


async def revoke_refresh(user_id: int | str, jti: str) -> None:
    await redis_client.delete(_refresh_key(user_id, jti))


async def revoke_all_refresh(user_id: int | str) -> int:
    """删除该用户所有 refresh（用于强制下线）。"""
    pattern = k("refresh", str(user_id), "*")
    deleted = 0
    async for key in redis_client.scan_iter(match=pattern, count=100):
        deleted += await redis_client.delete(key)
    return deleted
