"""Guest drafts capture an optional, normalised email and never echo it back."""
import pytest
from pydantic import ValidationError

from src.domain.guest_drafts.models import GuestDraft
from src.domain.guest_drafts.router import GuestDraftCreate, create_guest_draft


async def create(mock_db, **body):
    result = await create_guest_draft(GuestDraftCreate(**body), mock_db)
    saved = mock_db.add.call_args.args[0]
    assert isinstance(saved, GuestDraft)
    return saved, result


@pytest.mark.asyncio
async def test_email_is_stored_lowercased_and_trimmed(mock_db):
    saved, _ = await create(mock_db, prompt="Build a CRM", email="  Jane.Doe@Example.COM ")
    assert saved.email == "jane.doe@example.com"
    assert saved.prompt == "Build a CRM"


@pytest.mark.asyncio
@pytest.mark.parametrize("blank", [None, "", "   "])
async def test_email_is_optional_for_the_login_path(mock_db, blank):
    saved, _ = await create(mock_db, prompt="Build a CRM", email=blank)
    assert saved.email is None


@pytest.mark.asyncio
async def test_email_is_not_returned_to_the_caller(mock_db):
    _, result = await create(mock_db, prompt="Build a CRM", email="jane@example.com")
    assert set(result) == {"token", "expires_at", "understanding"}
    assert "jane@example.com" not in str(result)


@pytest.mark.parametrize("bad", ["not-an-email", "a@", "@b.com", "a b@c.com"])
def test_invalid_email_is_rejected(bad):
    with pytest.raises(ValidationError):
        GuestDraftCreate(prompt="Build a CRM", email=bad)


def test_prompt_only_payload_still_valid_for_existing_callers():
    """The Dash iframe builder and older clients send no email."""
    assert GuestDraftCreate(prompt="Build a CRM").email is None
