from __future__ import annotations

from fastapi.testclient import TestClient

from app.core.email import memory_mailer


def clear_sent_emails() -> None:
    memory_mailer.clear()


def latest_token(recipient: str, template: str) -> str:
    token = memory_mailer.latest_token(recipient, template)
    if not token:
        raise AssertionError(f"No {template} email sent to {recipient}")
    return token


def register_and_verify(client: TestClient, email: str, password: str = "Valid123") -> None:
    client.post("/api/v1/auth/register", json={"email": email, "password": password})
    token = latest_token(email, "verify_email")
    response = client.post("/api/v1/auth/verify-email", json={"token": token})
    assert response.status_code == 200


def register_verify_login(client: TestClient, email: str, password: str = "Valid123") -> dict[str, str]:
    register_and_verify(client, email, password)
    login = client.post("/api/v1/auth/login", json={"email": email, "password": password})
    assert login.status_code == 200
    return {"Authorization": f"Bearer {login.json()['access_token']}"}
