import logging
import uuid
from datetime import time

import pytest

from app.core import security
from app.core.config import settings
from app.models.delivery import CourierProfile
from app.models.device_token import DeviceToken
from app.models.user import User, UserRole
from app.services import push as push_service
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0961000001"
ADMIN_PHONE = "0961000002"
CUSTOMER_PHONE = "0961000003"
COURIER_PHONE = "0961000004"
SEED_PIN = "111111"

NEAR_BRANCH = {"latitude": 9.006, "longitude": 38.764}


def _seed_user(db_session, phone, name, role, pin=SEED_PIN, email=None):
    normalized = normalize_ethiopian_phone(phone)
    user = User(
        phone=normalized,
        name=name,
        email=email or f"{normalized.lstrip('+')}@example.com",
        role=role.value,
        pin_hash=security.hash_pin(pin),
        is_phone_verified=True,
        is_email_verified=True,
    )
    db_session.add(user)
    db_session.commit()
    db_session.refresh(user)
    return user


def _login(client, phone, pin=SEED_PIN) -> str:
    resp = client.post("/api/v1/auth/login", json={"identifier": phone, "pin": pin})
    assert resp.status_code == 200, resp.text
    return resp.json()["access_token"]


def _auth_headers(token: str) -> dict:
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture()
def supplier_token(client, db_session):
    _seed_user(db_session, SUPPLIER_PHONE, "A Supplier", UserRole.SUPPLIER)
    return _login(client, SUPPLIER_PHONE)


@pytest.fixture()
def admin_token(client, db_session):
    _seed_user(db_session, ADMIN_PHONE, "An Admin", UserRole.ADMIN)
    return _login(client, ADMIN_PHONE)


@pytest.fixture()
def customer_token(client, db_session):
    _seed_user(db_session, CUSTOMER_PHONE, "A Customer", UserRole.CUSTOMER)
    return _login(client, CUSTOMER_PHONE)


@pytest.fixture()
def courier(db_session):
    return _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)


@pytest.fixture()
def courier_token(client, courier):
    return _login(client, COURIER_PHONE)


@pytest.fixture()
def branch_and_item(client, supplier_token, admin_token):
    merchant = client.post(
        "/api/v1/merchants",
        json={"name": "Wow Burger"},
        headers=_auth_headers(supplier_token),
    ).json()
    branch = client.post(
        f"/api/v1/merchants/{merchant['id']}/branches",
        json={
            "name": "Bole Branch",
            "address": "Bole, Addis Ababa",
            "latitude": 9.005,
            "longitude": 38.763,
            "phone": "0911223344",
        },
        headers=_auth_headers(supplier_token),
    ).json()
    client.patch(
        f"/api/v1/branches/{branch['id']}/approve",
        json={"approval_status": "approved"},
        headers=_auth_headers(admin_token),
    )
    category = client.post(
        f"/api/v1/branches/{branch['id']}/categories",
        json={"name": "Mains"},
        headers=_auth_headers(supplier_token),
    ).json()
    item = client.post(
        f"/api/v1/branches/{branch['id']}/categories/{category['id']}/items",
        json={"name": "Beef Burger", "price": "150.00"},
        headers=_auth_headers(supplier_token),
    ).json()
    return branch, item


def _set_profile(db_session, courier_token, **fields):
    courier_id = uuid.UUID(security.decode_access_token(courier_token)["sub"])
    profile = (
        db_session.query(CourierProfile)
        .filter(CourierProfile.user_id == courier_id)
        .first()
    )
    for field, value in fields.items():
        setattr(profile, field, value)
    db_session.commit()


def _make_courier_available(client, db_session, courier_token, **location_overrides):
    location = {**NEAR_BRANCH, **location_overrides}
    resp = client.post(
        "/api/v1/courier/location", json=location, headers=_auth_headers(courier_token)
    )
    assert resp.status_code == 200, resp.text
    _set_profile(
        db_session,
        courier_token,
        is_online=True,
        shift_start=time.fromisoformat("00:00:00"),
        shift_end=time.fromisoformat("23:59:59"),
    )


def _checkout_delivery(client, customer_token, item):
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    return client.post(
        "/api/v1/orders/checkout",
        json={
            "delivery_mode": "delivery",
            "delivery_address": "Kazanchis, Addis Ababa",
            "delivery_latitude": 9.010,
            "delivery_longitude": 38.768,
            "payment_method": "cash",
        },
        headers=_auth_headers(customer_token),
    )


def _spy_notify_user(monkeypatch):
    calls = []

    def _fake(db, user_id, title, body, data=None):
        calls.append((user_id, title, body, data))

    monkeypatch.setattr(push_service, "notify_user", _fake)
    return calls


# --- Device token registration ----------------------------------------------


def test_register_device_token_creates_row(client, db_session, customer_token):
    resp = client.post(
        "/api/v1/notifications/device-tokens",
        json={"token": "tok-1", "platform": "android"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 204, resp.text

    device = db_session.query(DeviceToken).filter(DeviceToken.token == "tok-1").first()
    assert device is not None
    assert device.platform == "android"


def test_register_device_token_requires_auth(client):
    resp = client.post("/api/v1/notifications/device-tokens", json={"token": "tok-2"})
    assert resp.status_code == 401  # no Authorization header at all


def test_reregistering_same_token_moves_ownership(
    client, db_session, customer_token, courier_token
):
    client.post(
        "/api/v1/notifications/device-tokens",
        json={"token": "shared-device", "platform": "android"},
        headers=_auth_headers(customer_token),
    )
    client.post(
        "/api/v1/notifications/device-tokens",
        json={"token": "shared-device", "platform": "ios"},
        headers=_auth_headers(courier_token),
    )

    rows = (
        db_session.query(DeviceToken).filter(DeviceToken.token == "shared-device").all()
    )
    assert len(rows) == 1
    assert rows[0].platform == "ios"
    courier_id = uuid.UUID(security.decode_access_token(courier_token)["sub"])
    assert rows[0].user_id == courier_id


def test_unregister_device_token_removes_own_token(client, db_session, customer_token):
    client.post(
        "/api/v1/notifications/device-tokens",
        json={"token": "tok-3"},
        headers=_auth_headers(customer_token),
    )
    resp = client.delete(
        "/api/v1/notifications/device-tokens/tok-3",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 204, resp.text
    assert (
        db_session.query(DeviceToken).filter(DeviceToken.token == "tok-3").first()
        is None
    )


def test_unregister_device_token_noop_for_someone_elses_token(
    client, db_session, customer_token, courier_token
):
    client.post(
        "/api/v1/notifications/device-tokens",
        json={"token": "tok-4"},
        headers=_auth_headers(customer_token),
    )
    resp = client.delete(
        "/api/v1/notifications/device-tokens/tok-4",
        headers=_auth_headers(courier_token),
    )
    assert resp.status_code == 204, resp.text  # idempotent, not an error
    assert (
        db_session.query(DeviceToken).filter(DeviceToken.token == "tok-4").first()
        is not None
    )


# --- app.services.push --------------------------------------------------


def test_notify_user_is_noop_when_fcm_not_configured(
    db_session, customer_token, monkeypatch
):
    customer_id = uuid.UUID(security.decode_access_token(customer_token)["sub"])
    push_service.register_device_token(db_session, customer_id, "tok-x", "android")

    def _fail(*a, **k):
        raise AssertionError("should never call FCM when unconfigured")

    monkeypatch.setattr("httpx.post", _fail)
    push_service.notify_user(db_session, customer_id, "Title", "Body")  # no raise


def test_notify_user_sends_to_each_registered_device(
    db_session, customer_token, monkeypatch
):
    customer_id = uuid.UUID(security.decode_access_token(customer_token)["sub"])
    push_service.register_device_token(db_session, customer_id, "tok-a", "android")
    push_service.register_device_token(db_session, customer_id, "tok-b", "ios")

    monkeypatch.setattr(settings, "fcm_project_id", "yeneb-test")
    monkeypatch.setattr(settings, "fcm_service_account_json", "{}")
    monkeypatch.setattr(push_service, "_get_access_token", lambda: "fake-access-token")

    sent = []

    class _FakeResponse:
        status_code = 200

        def raise_for_status(self):
            pass

    def _fake_post(url, headers=None, json=None, timeout=None):
        sent.append((url, headers, json))
        return _FakeResponse()

    monkeypatch.setattr("httpx.post", _fake_post)

    push_service.notify_user(
        db_session, customer_id, "Hello", "World", data={"order_id": "123"}
    )

    assert len(sent) == 2
    tokens_sent = {call[2]["message"]["token"] for call in sent}
    assert tokens_sent == {"tok-a", "tok-b"}
    for _url, headers, body in sent:
        assert headers["Authorization"] == "Bearer fake-access-token"
        assert body["message"]["notification"] == {"title": "Hello", "body": "World"}
        assert body["message"]["data"] == {"order_id": "123"}


def test_notify_user_removes_token_fcm_reports_unregistered(
    db_session, customer_token, monkeypatch
):
    customer_id = uuid.UUID(security.decode_access_token(customer_token)["sub"])
    push_service.register_device_token(db_session, customer_id, "stale-tok", "android")

    monkeypatch.setattr(settings, "fcm_project_id", "yeneb-test")
    monkeypatch.setattr(settings, "fcm_service_account_json", "{}")
    monkeypatch.setattr(push_service, "_get_access_token", lambda: "fake-access-token")

    class _FakeResponse:
        status_code = 404
        text = "UNREGISTERED"

        def raise_for_status(self):
            raise AssertionError("shouldn't be reached for a 404")

    monkeypatch.setattr("httpx.post", lambda *a, **k: _FakeResponse())

    push_service.notify_user(db_session, customer_id, "Hello", "World")

    assert (
        db_session.query(DeviceToken).filter(DeviceToken.token == "stale-tok").first()
        is None
    )


# --- Order/delivery lifecycle wiring -----------------------------------


def test_cash_checkout_notifies_customer_and_branch_owner(
    client, db_session, monkeypatch, customer_token, supplier_token, branch_and_item
):
    _branch, item = branch_and_item
    calls = _spy_notify_user(monkeypatch)

    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    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

    customer_id = uuid.UUID(security.decode_access_token(customer_token)["sub"])
    supplier_id = uuid.UUID(security.decode_access_token(supplier_token)["sub"])
    recipients = {call[0] for call in calls}
    assert customer_id in recipients
    assert supplier_id in recipients

    customer_call = next(c for c in calls if c[0] == customer_id)
    assert customer_call[1] == "Order confirmed"
    supplier_call = next(c for c in calls if c[0] == supplier_id)
    assert supplier_call[1] == "New order"


def test_cash_checkout_emails_order_confirmation_when_customer_has_email(
    client, db_session, caplog, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 2},
        headers=_auth_headers(customer_token),
    )

    with caplog.at_level(logging.INFO):
        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

    confirmation_logs = [
        r
        for r in caplog.records
        if r.name == "yeneb.email" and "Order confirmed" in r.message
    ]
    assert len(confirmation_logs) == 1


def test_cash_checkout_skips_order_confirmation_email_without_customer_email(
    client, db_session, caplog, customer_token, branch_and_item
):
    customer_id = uuid.UUID(security.decode_access_token(customer_token)["sub"])
    customer = db_session.query(User).filter(User.id == customer_id).first()
    customer.email = None
    db_session.commit()

    _branch, item = branch_and_item
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )

    with caplog.at_level(logging.INFO):
        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 not any(
        r.name == "yeneb.email" and "Order confirmed" in r.message
        for r in caplog.records
    )


def test_order_status_change_notifies_customer(
    client, db_session, monkeypatch, customer_token, supplier_token, branch_and_item
):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    order = client.post(
        "/api/v1/orders/checkout",
        json={"delivery_mode": "takeaway", "payment_method": "cash"},
        headers=_auth_headers(customer_token),
    ).json()

    calls = _spy_notify_user(monkeypatch)
    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "preparing"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text

    customer_id = uuid.UUID(security.decode_access_token(customer_token)["sub"])
    assert len(calls) == 1
    assert calls[0][0] == customer_id
    assert calls[0][1] == "Order update"
    assert calls[0][3]["status"] == "preparing"


def test_delivery_offered_notifies_courier(
    client, db_session, monkeypatch, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    calls = _spy_notify_user(monkeypatch)

    resp = _checkout_delivery(client, customer_token, item)
    assert resp.status_code == 200, resp.text

    courier_id = uuid.UUID(security.decode_access_token(courier_token)["sub"])
    courier_calls = [c for c in calls if c[0] == courier_id]
    assert len(courier_calls) == 1
    assert courier_calls[0][1] == "New delivery offer"


def test_delivery_accept_pickup_deliver_notify_customer(
    client, db_session, monkeypatch, customer_token, courier_token, branch_and_item
):
    _branch, item = branch_and_item
    _make_courier_available(client, db_session, courier_token)
    order = _checkout_delivery(client, customer_token, item).json()
    offer = client.get(
        "/api/v1/courier/offers/current", headers=_auth_headers(courier_token)
    ).json()

    calls = _spy_notify_user(monkeypatch)
    client.post(
        f"/api/v1/courier/offers/{offer['id']}/accept",
        headers=_auth_headers(courier_token),
    )
    client.post(
        f"/api/v1/courier/deliveries/{offer['id']}/picked-up",
        headers=_auth_headers(courier_token),
    )
    client.post(
        f"/api/v1/courier/deliveries/{offer['id']}/delivered",
        headers=_auth_headers(courier_token),
    )

    customer_id = uuid.UUID(security.decode_access_token(customer_token)["sub"])
    titles = [c[1] for c in calls if c[0] == customer_id]
    assert titles == ["Courier on the way", "Order picked up", "Order delivered"]
    assert all(c[3]["order_id"] == order["id"] for c in calls if c[0] == customer_id)
