"""Phone normalisation (task 2.7, spec rsvp-flow FR-2.3)."""

import pytest

from app.services.phone import (
    InvalidPhoneNumberError,
    normalize_email,
    normalize_phone,
    try_normalize_phone,
)


@pytest.mark.parametrize(
    "raw",
    [
        "01712345678",
        "+8801712345678",
        "8801712345678",
        "01712-345678",
        " 01712 345 678 ",
    ],
)
def test_bangladeshi_numbers_normalise_to_one_form(raw: str) -> None:
    """Every way a guest might type their number must land on the same stored value —
    deduplication depends on string equality."""
    assert normalize_phone(raw) == "+8801712345678"


def test_empty_input_is_not_an_error() -> None:
    """Phone is optional on some paths; blank means absent, not invalid."""
    assert normalize_phone(None) is None
    assert normalize_phone("") is None
    assert normalize_phone("   ") is None


@pytest.mark.parametrize("raw", ["12345", "0171234", "not a phone", "017123456789999"])
def test_invalid_numbers_raise(raw: str) -> None:
    """Rejected inline at the form rather than stored and silently unsendable."""
    with pytest.raises(InvalidPhoneNumberError):
        normalize_phone(raw)


def test_bulk_import_variant_does_not_raise() -> None:
    """One malformed row must not abort an 800-row CSV import."""
    assert try_normalize_phone("nonsense") is None
    assert try_normalize_phone("01712345678") == "+8801712345678"


def test_international_numbers_are_accepted() -> None:
    """Relatives abroad still need to be reachable."""
    assert normalize_phone("+442071838750") == "+442071838750"


def test_email_normalisation_matches_the_unique_index() -> None:
    """The guest uniqueness index is on lower(email); every write path must agree."""
    assert normalize_email("  Rahim@Example.COM ") == "rahim@example.com"
    assert normalize_email("") is None
    assert normalize_email(None) is None
