import hashlib
import hmac
import json
import uuid

import pytest

from app.core import security
from app.models.order import Order, OrderStatus, PaymentStatus
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0960000001"
ADMIN_PHONE = "0960000002"
CUSTOMER_PHONE = "0960000003"
SEED_PIN = "111111"
WEBHOOK_SECRET = "test-webhook-secret"


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(db_session):
    return _seed_user(db_session, SUPPLIER_PHONE, "A Supplier", UserRole.SUPPLIER)


@pytest.fixture()
def supplier_token(client, 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 order(client, db_session, supplier_token, admin_token, customer_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()
    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": "takeaway"},
        headers=_auth_headers(customer_token),
    ).json()


def _sign(body: dict) -> tuple[bytes, str]:
    raw = json.dumps(body).encode()
    signature = hmac.new(WEBHOOK_SECRET.encode(), raw, hashlib.sha256).hexdigest()
    return raw, signature


def _post_webhook(client, raw_body: bytes, signature: str | None):
    headers = {"Content-Type": "application/json"}
    if signature is not None:
        headers["x-chapa-signature"] = signature
    return client.post("/api/v1/webhooks/chapa", content=raw_body, headers=headers)


def test_webhook_rejects_missing_signature(client, order):
    raw, _sig = _sign({"tx_ref": order["tx_ref"], "event": "charge.success"})
    resp = _post_webhook(client, raw, None)
    assert resp.status_code == 401


def test_webhook_rejects_invalid_signature(client, monkeypatch, order):
    from app.core.config import settings

    monkeypatch.setattr(settings, "chapa_webhook_secret", WEBHOOK_SECRET)
    raw, _sig = _sign({"tx_ref": order["tx_ref"], "event": "charge.success"})
    resp = _post_webhook(client, raw, "not-the-real-signature")
    assert resp.status_code == 401


def test_webhook_ignores_unknown_tx_ref(client, monkeypatch):
    from app.core.config import settings

    monkeypatch.setattr(settings, "chapa_webhook_secret", WEBHOOK_SECRET)
    raw, sig = _sign({"tx_ref": "yeneb-does-not-exist", "event": "charge.success"})
    resp = _post_webhook(client, raw, sig)
    assert resp.status_code == 200
    assert resp.json()["status"] == "ignored"


def test_webhook_marks_order_paid_on_verified_success(
    client, db_session, monkeypatch, order
):
    from app.core.config import settings
    from app.services.payments import chapa as chapa_service

    monkeypatch.setattr(settings, "chapa_webhook_secret", WEBHOOK_SECRET)
    monkeypatch.setattr(
        chapa_service, "verify_payment", lambda tx_ref: {"status": "success"}
    )

    raw, sig = _sign(
        {
            "tx_ref": order["tx_ref"],
            "event": "charge.success",
            "payment_method": "telebirr",
        }
    )
    resp = _post_webhook(client, raw, sig)
    assert resp.status_code == 200
    assert resp.json()["status"] == "processed"

    db_order = (
        db_session.query(Order).filter(Order.id == uuid.UUID(order["id"])).first()
    )
    assert db_order.payment_status == PaymentStatus.PAID.value
    assert db_order.status == OrderStatus.CONFIRMED.value
    assert db_order.payment_method == "telebirr"


def test_webhook_marks_order_failed_when_verification_disagrees(
    client, db_session, monkeypatch, order
):
    """A signature can be valid while the transaction itself still
    isn't actually successful — the independent re-verification call
    is what actually decides the outcome, not the payload alone."""
    from app.core.config import settings
    from app.services.payments import chapa as chapa_service

    monkeypatch.setattr(settings, "chapa_webhook_secret", WEBHOOK_SECRET)
    monkeypatch.setattr(
        chapa_service, "verify_payment", lambda tx_ref: {"status": "failed"}
    )

    raw, sig = _sign({"tx_ref": order["tx_ref"], "event": "charge.success"})
    resp = _post_webhook(client, raw, sig)
    assert resp.status_code == 200

    db_order = (
        db_session.query(Order).filter(Order.id == uuid.UUID(order["id"])).first()
    )
    assert db_order.payment_status == PaymentStatus.FAILED.value
    assert db_order.status == OrderStatus.PENDING_PAYMENT.value


def test_webhook_is_idempotent_on_duplicate_delivery(
    client, db_session, monkeypatch, order
):
    from app.core.config import settings
    from app.services.payments import chapa as chapa_service

    monkeypatch.setattr(settings, "chapa_webhook_secret", WEBHOOK_SECRET)
    calls = []

    def fake_verify(tx_ref):
        calls.append(tx_ref)
        return {"status": "success"}

    monkeypatch.setattr(chapa_service, "verify_payment", fake_verify)

    raw, sig = _sign({"tx_ref": order["tx_ref"], "event": "charge.success"})
    first = _post_webhook(client, raw, sig)
    second = _post_webhook(client, raw, sig)

    assert first.status_code == 200
    assert second.status_code == 200
    assert second.json()["status"] == "already processed"
    assert len(calls) == 1  # only re-verified once, not on the duplicate delivery
