from __future__ import annotations

from datetime import UTC, datetime, timedelta

from app.core.database import session_scope
from app.db.token_cleanup import cleanup_expired_tokens
from app.modules.auth.models import EmailVerificationToken, PasswordResetToken, RefreshToken
from app.modules.users.repository import get_user_by_email


def test_cleanup_expired_tokens_removes_stale_rows():
    user = get_user_by_email("admin@compton.example")
    now = datetime.now(UTC)
    with session_scope() as db:
        db.add(
            RefreshToken(
                user_id=user.id,
                token_hash="f" * 64,
                family_id="fam-cleanup-1",
                expires_at=now - timedelta(days=2),
                revoked_at=now - timedelta(days=2),
            )
        )
        db.add(
            PasswordResetToken(
                user_id=user.id,
                token_hash="e" * 64,
                expires_at=now - timedelta(days=1),
                used_at=None,
            )
        )
        db.add(
            EmailVerificationToken(
                user_id=user.id,
                token_hash="d" * 64,
                expires_at=now - timedelta(days=1),
                used_at=None,
            )
        )

    result = cleanup_expired_tokens(retention_days=1)
    assert result["refresh_tokens_deleted"] >= 1
    assert result["password_reset_tokens_deleted"] >= 1
    assert result["email_verification_tokens_deleted"] >= 1
