"""
contact_phone on POST /api/v1/sales/opportunities was free-form (no format
enforced), unlike purchaser_phone (contracts) and sender_phone (log-call)
which both run through validate_phone(). This let malformed numbers into the
same field ContractWizardModal later has to guard against on the frontend
("only pre-populate phone if it already matches the canonical format").
"""
import pytest
from httpx import AsyncClient

OPPS_URL = "/api/v1/sales/opportunities"


def _tenant_headers(token: str, tenant_id: str):
    return {
        "Authorization": f"Bearer {token}",
        "X-Tenant-ID": tenant_id,
    }


@pytest.mark.asyncio
async def test_create_opportunity_normalizes_lenient_phone(
    client: AsyncClient, admin_token: str, test_account,
):
    """Unformatted-but-parseable phone is normalized to (NXX) NXX-XXXX."""
    resp = await client.post(
        OPPS_URL,
        json={
            "family_name": "Okafor Family",
            "care_type": "pre_need",
            "contact_phone": "6135550100",
        },
        headers=_tenant_headers(admin_token, str(test_account.id)),
    )
    assert resp.status_code == 201
    assert resp.json()["data"]["contact_phone"] == "(613) 555-0100"


@pytest.mark.asyncio
async def test_create_opportunity_rejects_invalid_phone(
    client: AsyncClient, admin_token: str, test_account,
):
    """A phone that can't be parsed into 10 digits → 422, not silently stored."""
    resp = await client.post(
        OPPS_URL,
        json={
            "family_name": "Okafor Family",
            "care_type": "pre_need",
            "contact_phone": "12345",
        },
        headers=_tenant_headers(admin_token, str(test_account.id)),
    )
    assert resp.status_code == 422


@pytest.mark.asyncio
async def test_create_opportunity_phone_still_optional(
    client: AsyncClient, admin_token: str, test_account,
):
    """Omitting contact_phone entirely is unaffected by the added validation."""
    resp = await client.post(
        OPPS_URL,
        json={"family_name": "Okafor Family", "care_type": "pre_need"},
        headers=_tenant_headers(admin_token, str(test_account.id)),
    )
    assert resp.status_code == 201
    assert resp.json()["data"]["contact_phone"] is None
