from datetime import timedelta

import redis as redis_lib
from sqlalchemy.orm import Session

from app.core import security
from app.core.config import settings
from app.models.refresh_token import RefreshToken
from app.models.user import User
from app.services import token_blacklist
from app.utils.time import utcnow


class RefreshTokenError(Exception):
    """A refresh token couldn't be accepted as submitted."""


def issue_refresh_token(db: Session, user: User) -> str:
    token = security.generate_refresh_token()
    db.add(
        RefreshToken(
            user_id=user.id,
            token_hash=security.hash_refresh_token(token),
            expires_at=utcnow() + timedelta(days=settings.refresh_token_expire_days),
        )
    )
    db.commit()
    return token


def rotate_refresh_token(
    db: Session, redis: redis_lib.Redis, token: str
) -> tuple[User, str]:
    """Validate a refresh token, revoke it, and issue a replacement.

    If a token that's already been revoked is presented again, every
    active refresh token for that user is revoked too: reuse of a dead
    token is a strong signal it was stolen, so the whole session family
    is killed rather than trusting it. That covers future refresh
    calls, but does nothing about an access token issued earlier that
    might still be live for up to access_token_expire_minutes — so this
    also blacklists every access token for this user via
    app.services.token_blacklist.invalidate_all_sessions, closing the
    same gap on the access-token side.
    """
    token_hash = security.hash_refresh_token(token)
    record = (
        db.query(RefreshToken).filter(RefreshToken.token_hash == token_hash).first()
    )

    if record is None:
        raise RefreshTokenError("Invalid refresh token.")

    if record.revoked_at is not None:
        db.query(RefreshToken).filter(
            RefreshToken.user_id == record.user_id,
            RefreshToken.revoked_at.is_(None),
        ).update({"revoked_at": utcnow()})
        db.commit()
        token_blacklist.invalidate_all_sessions(
            redis, record.user_id, settings.access_token_expire_minutes * 60
        )
        raise RefreshTokenError(
            "This refresh token was already used. All sessions for this "
            "account have been signed out — log in again."
        )

    if record.expires_at < utcnow():
        raise RefreshTokenError("Refresh token has expired. Log in again.")

    user = db.get(User, record.user_id)
    if user is None or not user.is_active:
        raise RefreshTokenError("Invalid refresh token.")

    record.revoked_at = utcnow()
    db.commit()

    new_token = issue_refresh_token(db, user)
    return user, new_token


def revoke_refresh_token(db: Session, token: str) -> None:
    """Revoke a refresh token (logout). Silently no-ops if it's unknown
    or already revoked, so logout is idempotent."""
    token_hash = security.hash_refresh_token(token)
    record = (
        db.query(RefreshToken).filter(RefreshToken.token_hash == token_hash).first()
    )
    if record is not None and record.revoked_at is None:
        record.revoked_at = utcnow()
        db.commit()
