from fastapi.testclient import TestClient

from app.core.config import settings
from app.core.email import memory_mailer
from app.main import create_app


def _test_client(monkeypatch) -> TestClient:
    monkeypatch.setattr(settings, "enable_test_routes", True)
    monkeypatch.setattr(settings, "email_delivery_mode", "memory")
    return TestClient(create_app())


def test_latest_email_token_route(monkeypatch):
    client = _test_client(monkeypatch)
    memory_mailer.clear()
    memory_mailer.send(
        to="token-route@example.com",
        subject="Verify",
        body="TOKEN:route-token\n",
        template="verify_email",
    )
    response = client.get(
        "/api/v1/test/emails/latest-token",
        params={"to": "token-route@example.com", "template": "verify_email"},
    )
    assert response.status_code == 200
    assert response.json()["token"] == "route-token"


def test_latest_email_token_route_missing_token(monkeypatch):
    client = _test_client(monkeypatch)
    response = client.get(
        "/api/v1/test/emails/latest-token",
        params={"to": "missing@example.com", "template": "verify_email"},
    )
    assert response.status_code == 404
    assert response.json()["detail"] == "TOKEN_NOT_FOUND"
