"""Shared auth Redis connection (DB 15).

All cross-app auth keys live here so that per-app FLUSHDB on deploy
doesn't wipe SSO state:
  - did_auth:{device_id}   — login signal timestamp
  - grant:{grant_token}    — grant validity cache (ok/revoked)
  - prompt:{app}:{device_id} — prompt=none cooldown
"""
from __future__ import annotations

import os

from redis import asyncio as aioredis

_AUTH_REDIS_URL = os.getenv("REDIS_AUTH_URL", "redis://redis:6379/15")

_auth_redis: aioredis.Redis | None = None


async def get_auth_redis() -> aioredis.Redis:
    """Return the shared auth Redis connection (lazy init)."""
    global _auth_redis
    if _auth_redis is None:
        _auth_redis = aioredis.Redis.from_url(
            _AUTH_REDIS_URL,
            encoding="utf-8",
            decode_responses=False,
        )
    return _auth_redis


async def close_auth_redis() -> None:
    """Close the auth Redis connection (call on app shutdown)."""
    global _auth_redis
    if _auth_redis is not None:
        await _auth_redis.close()
        _auth_redis = None
