"""Hydrate Redis refresh-token sets from MySQL after Redis restart."""

from __future__ import annotations

import logging

from server.application.services.auth_service import REFRESH_TOKEN_REDIS_PREFIX, _refresh_token_expire_days
from server.infrastructure.database.refresh_token_repo import RefreshTokenRepositoryImpl
from server.infrastructure.database.session import AsyncSessionLocal

logger = logging.getLogger("nexus.refresh_token_hydration")


async def hydrate_refresh_tokens_from_mysql() -> None:
    """Load valid refresh token hashes from MySQL into Redis (primary worker startup)."""
    from server.infrastructure.redis.client import get_redis

    try:
        redis = get_redis()
    except Exception as e:
        logger.warning("Skip refresh token hydration — Redis unavailable: %s", e)
        return

    async with AsyncSessionLocal() as session:
        repo = RefreshTokenRepositoryImpl(session)
        removed = await repo.delete_expired()
        grouped = await repo.list_valid_grouped()

    if removed:
        logger.info("Purged %d expired refresh token row(s) from MySQL", removed)

    if not grouped:
        logger.info("No refresh tokens to hydrate from MySQL")
        return

    ttl_seconds = _refresh_token_expire_days() * 86400 + 3600
    total = 0
    for admin_id, hashes in grouped.items():
        key = f"{REFRESH_TOKEN_REDIS_PREFIX}{admin_id}"
        if hashes:
            await redis.sadd(key, *hashes)
            await redis.expire(key, ttl_seconds)
            total += len(hashes)

    logger.info(
        "Hydrated %d refresh token hash(es) for %d admin(s) from MySQL → Redis",
        total,
        len(grouped),
    )
