from app.core.config import settings
from app.models.user import UserRole
from app.services import push as push_service
from app.services import sms as sms_service

from .test_orders import (  # noqa: F401 (fixture imports, used by name via injection)
    _add_to_cart,
    _auth_headers,
    _seed_user,
    admin_token,
    branch_and_item,
    customer_token,
    supplier,
    supplier_token,
)

# Addis Ababa — inside Ethiopia's bounding box.
_ETHIOPIA_COORDS = {"delivery_latitude": 9.010, "delivery_longitude": 38.768}
# New York — well outside it.
_FOREIGN_COORDS = {"delivery_latitude": 40.7128, "delivery_longitude": -74.0060}


def _gift_checkout(client, token, **overrides):
    payload = {
        "delivery_mode": "delivery",
        "delivery_address": "Kazanchis, Addis Ababa",
        "payment_method": "cash",
        "recipient_name": "Marta",
        "recipient_phone": "0911223344",
        **_ETHIOPIA_COORDS,
    }
    payload.update(overrides)
    return client.post(
        "/api/v1/orders/checkout", json=payload, headers=_auth_headers(token)
    )


def test_checkout_accepts_a_valid_order_for_a_friend(
    client,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    resp = _gift_checkout(client, customer_token)
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["recipient_name"] == "Marta"
    assert body["recipient_phone"] == "+251911223344"
    assert body["delivery_address"] == "Kazanchis, Addis Ababa"


def test_checkout_rejects_recipient_phone_without_name(
    client,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    resp = _gift_checkout(client, customer_token, recipient_name=None)
    assert resp.status_code == 422


def test_checkout_rejects_recipient_name_without_phone(
    client,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    resp = _gift_checkout(client, customer_token, recipient_phone=None)
    assert resp.status_code == 422


def test_checkout_rejects_gift_order_for_takeaway(
    client,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    resp = _gift_checkout(
        client,
        customer_token,
        delivery_mode="takeaway",
        delivery_latitude=None,
        delivery_longitude=None,
    )
    assert resp.status_code == 422


def test_checkout_rejects_recipient_address_outside_ethiopia(
    client,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    resp = _gift_checkout(client, customer_token, **_FOREIGN_COORDS)
    assert resp.status_code == 422


def test_checkout_rejects_invalid_recipient_phone(
    client,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    resp = _gift_checkout(client, customer_token, recipient_phone="not-a-phone")
    assert resp.status_code == 422


def test_regular_delivery_order_does_not_require_recipient_fields(
    client,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    """A normal delivery order (no recipient fields at all) is
    unaffected — the address-in-Ethiopia rule only kicks in for a
    gift order, not every delivery."""
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    resp = client.post(
        "/api/v1/orders/checkout",
        json={
            "delivery_mode": "delivery",
            "delivery_address": "Somewhere abroad, entered by mistake",
            "delivery_latitude": _FOREIGN_COORDS["delivery_latitude"],
            "delivery_longitude": _FOREIGN_COORDS["delivery_longitude"],
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["recipient_name"] is None


def test_gift_order_sends_sms_to_recipient_on_confirmation(
    client,
    monkeypatch,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    sent = []
    monkeypatch.setattr(
        sms_service, "send_sms", lambda phone, message: sent.append((phone, message))
    )

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    resp = _gift_checkout(client, customer_token)
    assert resp.status_code == 200, resp.text

    assert len(sent) == 1
    phone, message = sent[0]
    assert phone == "+251911223344"
    assert "Marta" in message
    assert "Kazanchis, Addis Ababa" in message
    # app_download_url is unset by default (real Play Store link isn't
    # live yet) — the SMS must not reference one that doesn't exist.
    assert "http" not in message


def test_gift_sms_recommends_the_app_to_an_unregistered_recipient_when_configured(
    client,
    monkeypatch,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    monkeypatch.setattr(settings, "app_download_url", "https://play.google.com/yeneb")
    sent = []
    monkeypatch.setattr(
        sms_service, "send_sms", lambda phone, message: sent.append((phone, message))
    )

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    resp = _gift_checkout(client, customer_token)
    assert resp.status_code == 200, resp.text

    assert len(sent) == 1
    assert "https://play.google.com/yeneb" in sent[0][1]


def test_gift_sms_skips_the_app_link_for_an_already_registered_recipient(
    client,
    db_session,
    monkeypatch,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    _seed_user(db_session, "0911223344", "Marta The Recipient", UserRole.CUSTOMER)
    monkeypatch.setattr(settings, "app_download_url", "https://play.google.com/yeneb")
    sent = []
    monkeypatch.setattr(
        sms_service, "send_sms", lambda phone, message: sent.append((phone, message))
    )
    monkeypatch.setattr(push_service, "notify_user", lambda *a, **k: None)

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    resp = _gift_checkout(client, customer_token)
    assert resp.status_code == 200, resp.text

    assert len(sent) == 1
    assert "https://play.google.com/yeneb" not in sent[0][1]


def test_regular_order_does_not_sms_anyone(
    client,
    monkeypatch,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    sent = []
    monkeypatch.setattr(
        sms_service, "send_sms", lambda phone, message: sent.append((phone, message))
    )

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    resp = client.post(
        "/api/v1/orders/checkout",
        json={"delivery_mode": "takeaway", "payment_method": "cash"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert sent == []


def _spy_notify_user(monkeypatch):
    calls = []
    monkeypatch.setattr(
        push_service,
        "notify_user",
        lambda db, user_id, title, body, data=None: calls.append(
            (user_id, title, body, data)
        ),
    )
    return calls


def test_gift_order_also_pushes_a_registered_recipient(
    client,
    db_session,
    monkeypatch,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    """The recipient doesn't have to be a Yeneb user for the gift to
    work (SMS alone covers that) — but if recipient_phone happens to
    match a registered account, they get a push too, on top of the
    SMS, not instead of it."""
    recipient = _seed_user(
        db_session, "0911223344", "Marta The Recipient", UserRole.CUSTOMER
    )
    sms_sent = []
    monkeypatch.setattr(
        sms_service,
        "send_sms",
        lambda phone, message: sms_sent.append((phone, message)),
    )
    push_calls = _spy_notify_user(monkeypatch)

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    resp = _gift_checkout(client, customer_token)
    assert resp.status_code == 200, resp.text

    assert len(sms_sent) == 1  # SMS still goes out regardless
    gift_pushes = [c for c in push_calls if c[3]["type"] == "gift_order_incoming"]
    assert len(gift_pushes) == 1
    user_id, _title, _body, _data = gift_pushes[0]
    assert user_id == recipient.id


def test_gift_order_skips_push_for_an_unregistered_recipient(
    client,
    monkeypatch,
    customer_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    push_calls = _spy_notify_user(monkeypatch)
    monkeypatch.setattr(sms_service, "send_sms", lambda phone, message: None)

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    resp = _gift_checkout(client, customer_token)
    assert resp.status_code == 200, resp.text
    gift_pushes = [c for c in push_calls if c[3]["type"] == "gift_order_incoming"]
    assert gift_pushes == []
