from unittest.mock import MagicMock, patch

import pytest

from app.core import jwt_denylist as denylist_module
from app.core.jwt_denylist import (
    bump_auth_epoch,
    deny_jti,
    ensure_jwt_revocation_backend,
    get_auth_epoch,
    is_jti_denied,
)


def test_ensure_jwt_revocation_backend_requires_redis_in_production(monkeypatch):
    monkeypatch.setattr(denylist_module.settings, "app_env", "production")
    with patch("app.core.jwt_denylist.get_redis_client", return_value=None):
        with pytest.raises(RuntimeError, match="Redis is required"):
            ensure_jwt_revocation_backend()


def test_redis_auth_epoch_roundtrip():
    mock_client = MagicMock()
    mock_client.get.return_value = "3"
    mock_client.incr.return_value = 4
    with patch("app.core.jwt_denylist.get_redis_client", return_value=mock_client):
        assert get_auth_epoch("user-1") == 3
        assert bump_auth_epoch("user-1") == 4
        mock_client.incr.assert_called_once()


def test_redis_deny_jti_and_check():
    mock_client = MagicMock()
    with patch("app.core.jwt_denylist.get_redis_client", return_value=mock_client):
        with patch("app.core.jwt_denylist.time.time", return_value=1000):
            deny_jti("abc-jti", 1060)
        mock_client.setex.assert_called_once_with("jwt:deny:abc-jti", 60, "1")
        mock_client.exists.return_value = 1
        assert is_jti_denied("abc-jti") is True


def test_forgot_password_skips_blocked_user(client):
    from app.modules.users.repository import create_user, get_user_by_email, update_user
    from app.core.security import hash_password

    create_user("blocked-forgot@example.com", hash_password("Valid123"), status="active")
    user = get_user_by_email("blocked-forgot@example.com")
    user.status = "blocked"
    update_user(user)

    response = client.post(
        "/api/v1/auth/forgot-password",
        json={"email": "blocked-forgot@example.com"},
    )
    assert response.status_code == 200
    from app.core.email import memory_mailer

    assert not any(msg.to == "blocked-forgot@example.com" for msg in memory_mailer.sent)


def test_logout_revokes_access_token(client):
    from tests.helpers import register_and_verify

    register_and_verify(client, "logout-jti@example.com")
    login = client.post(
        "/api/v1/auth/login",
        json={"email": "logout-jti@example.com", "password": "Valid123"},
    )
    token = login.json()["access_token"]
    logout = client.post(
        "/api/v1/auth/logout",
        headers={"Authorization": f"Bearer {token}", "Origin": "http://localhost:5173"},
    )
    assert logout.status_code == 200
    me = client.get("/api/v1/users/me", headers={"Authorization": f"Bearer {token}"})
    assert me.status_code == 401
    assert me.json()["detail"] == "TOKEN_REVOKED"
