import uuid
from datetime import timezone

import redis as redis_lib

from app.core import security
from app.utils.time import utcnow


def _unix_now() -> int:
    # utcnow() returns a *naive* datetime — calling .timestamp() on it
    # directly would have Python interpret it as local time, not UTC,
    # silently shifting every timestamp in this file by the server's
    # UTC offset. Same fix app.core.security.create_access_token
    # already applies to its own exp/iat claims; this has to match it
    # exactly; a mismatch here is exactly the kind of bug that produces
    # a blacklist entry that looks right but never actually matches.
    return int(utcnow().replace(tzinfo=timezone.utc).timestamp())


def _token_key(token: str) -> str:
    # Same hash used for refresh tokens (app.core.security) — the raw
    # token is never stored, only its digest, so a Redis dump doesn't
    # hand out anything usable on its own.
    return f"blacklist:access_token:{security.sha256_hash(token)}"


def _user_invalidated_before_key(user_id: uuid.UUID) -> str:
    return f"blacklist:user_invalidated_before:{user_id}"


def blacklist_access_token(redis: redis_lib.Redis, token: str, exp: int) -> None:
    """Called from /auth/logout. `exp` is the token's own `exp` claim
    (unix timestamp) — the blacklist entry's TTL is set to exactly the
    token's remaining lifetime, so it never outlives the token it's
    blocking and Redis never accumulates entries for tokens that have
    already naturally expired. A no-op if the token is already expired
    (nothing left to block)."""
    ttl = exp - _unix_now()
    if ttl <= 0:
        return
    redis.setex(_token_key(token), ttl, "1")


def is_access_token_blacklisted(redis: redis_lib.Redis, token: str) -> bool:
    return redis.exists(_token_key(token)) > 0


def invalidate_all_sessions(
    redis: redis_lib.Redis, user_id: uuid.UUID, ttl_seconds: int
) -> None:
    """Called when refresh-token reuse is detected (see
    app.services.tokens.rotate_refresh_token) — that already revokes
    every refresh token for this user in Postgres, but does nothing
    about an access token issued earlier that's still within its
    lifetime. This closes that gap: any access token whose `iat` is
    before "now" is rejected by get_current_user from this point on,
    regardless of which specific token it is — the whole session
    family, not just the one that was reused.

    ttl_seconds should be settings.access_token_expire_minutes * 60 —
    once that much time has passed, no access token issued before this
    call could still be unexpired anyway, so the marker can safely
    expire itself rather than grow this key forever."""
    redis.setex(_user_invalidated_before_key(user_id), ttl_seconds, str(_unix_now()))


def get_user_invalidated_before(
    redis: redis_lib.Redis, user_id: uuid.UUID
) -> int | None:
    raw = redis.get(_user_invalidated_before_key(user_id))
    return int(raw) if raw is not None else None
