from __future__ import annotations

from tests.helpers import register_and_verify


def _admin_headers(client) -> dict[str, str]:
    from app.core.security import create_access_token
    from app.modules.users.repository import get_user_by_email

    admin = get_user_by_email("admin@compton.example")
    token = create_access_token(admin.id, admin.role, admin.is_superuser)
    return {"Authorization": f"Bearer {token}"}


def test_refresh_fails_for_pending_user(client):
    client.post(
        "/api/v1/auth/register",
        json={"email": "pending-refresh@example.com", "password": "Valid123"},
    )
    login = client.post(
        "/api/v1/auth/login",
        json={"email": "pending-refresh@example.com", "password": "Valid123"},
    )
    assert login.status_code == 403
    assert login.json()["detail"] == "EMAIL_NOT_VERIFIED"

    # Simulate stale refresh cookie from an earlier active session edge case via direct token issue.
    from app.modules.auth.service import issue_refresh_token
    from app.modules.users.repository import get_user_by_email

    user = get_user_by_email("pending-refresh@example.com")
    refresh_token = issue_refresh_token(user.id)
    client.cookies.set("refresh_token", refresh_token, path="/api/v1/auth")

    refresh = client.post("/api/v1/auth/refresh", headers={"Origin": "http://localhost:5173"})
    assert refresh.status_code == 403
    assert refresh.json()["detail"] == "EMAIL_NOT_VERIFIED"


def test_refresh_fails_for_blocked_user(client):
    register_and_verify(client, "blocked-refresh@example.com")
    login = client.post(
        "/api/v1/auth/login",
        json={"email": "blocked-refresh@example.com", "password": "Valid123"},
    )
    assert login.status_code == 200
    admin_headers = _admin_headers(client)
    me = client.get(
        "/api/v1/users/me",
        headers={"Authorization": f"Bearer {login.json()['access_token']}"},
    )
    user_id = me.json()["user"]["id"]
    blocked = client.patch(
        f"/api/v1/admin/users/{user_id}",
        headers=admin_headers,
        json={"status": "blocked"},
    )
    assert blocked.status_code == 200
    refresh = client.post("/api/v1/auth/refresh", headers={"Origin": "http://localhost:5173"})
    assert refresh.status_code == 403
    assert refresh.json()["detail"] == "ACCOUNT_BLOCKED"


def test_refresh_requires_origin_header_when_cookie_present(client):
    register_and_verify(client, "origin-required@example.com")
    login = client.post(
        "/api/v1/auth/login",
        json={"email": "origin-required@example.com", "password": "Valid123"},
    )
    assert login.status_code == 200
    response = client.post("/api/v1/auth/refresh")
    assert response.status_code == 403
    assert response.json()["detail"] == "INVALID_ORIGIN"
