import hashlib
import hmac
import json
import uuid
from decimal import Decimal

from app.models.cart import CartItem
from app.models.order import Order, OrderStatus, PaymentStatus

from .test_orders import (  # noqa: F401 (fixture imports, used by name via injection)
    _auth_headers,
    admin_token,
    branch_and_item,
    customer2_token,
    customer_token,
    supplier,
    supplier_token,
)

WEBHOOK_SECRET = "test-webhook-secret"


def _start(client, token, **overrides):
    resp = client.post(
        "/api/v1/cart/group-sessions", json=overrides, headers=_auth_headers(token)
    )
    assert resp.status_code == 200, resp.text
    return resp.json()


def _join(client, token, join_code):
    return client.post(
        "/api/v1/cart/group-sessions/join",
        json={"join_code": join_code},
        headers=_auth_headers(token),
    )


def _add(client, token, item, session_id, quantity=1):
    return client.post(
        "/api/v1/cart/items",
        json={
            "menu_item_id": item["id"],
            "quantity": quantity,
            "group_session_id": session_id,
        },
        headers=_auth_headers(token),
    )


def _lock(client, token, session_id, **overrides):
    payload = {"delivery_mode": "takeaway"}
    payload.update(overrides)
    return client.post(
        f"/api/v1/cart/group-sessions/{session_id}/lock",
        json=payload,
        headers=_auth_headers(token),
    )


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):
    return client.post(
        "/api/v1/webhooks/chapa",
        content=raw_body,
        headers={"Content-Type": "application/json", "x-chapa-signature": signature},
    )


def _user_id(client, token) -> str:
    resp = client.get("/api/v1/customer/profile", headers=_auth_headers(token))
    assert resp.status_code == 200, resp.text
    return resp.json()["user_id"]


# --- Session lifecycle -----------------------------------------------------


def test_start_session_creates_open_session_with_join_code(
    client,
    customer_token,  # noqa: F811
):
    session = _start(client, customer_token)
    assert session["status"] == "open"
    assert len(session["join_code"]) == 6


def test_cannot_start_a_second_active_session_on_the_same_cart(
    client,
    customer_token,  # noqa: F811
):
    _start(client, customer_token)
    resp = client.post(
        "/api/v1/cart/group-sessions", json={}, headers=_auth_headers(customer_token)
    )
    assert resp.status_code == 409


def test_join_session_by_code_adds_participant(
    client,
    customer_token,
    customer2_token,  # noqa: F811
):
    session = _start(client, customer_token)
    resp = _join(client, customer2_token, session["join_code"])
    assert resp.status_code == 200, resp.text
    names = [p["name"] for p in resp.json()["participants"]]
    assert names == ["Another Customer"]


def test_join_requires_a_valid_code(client, customer2_token):  # noqa: F811
    resp = _join(client, customer2_token, "NOPE00")
    assert resp.status_code == 404


def test_host_cannot_join_their_own_session(
    client,
    customer_token,  # noqa: F811
):
    session = _start(client, customer_token)
    resp = _join(client, customer_token, session["join_code"])
    assert resp.status_code == 409


def test_joining_twice_is_idempotent(
    client,
    customer_token,
    customer2_token,  # noqa: F811
):
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    resp = _join(client, customer2_token, session["join_code"])
    assert resp.status_code == 200
    assert len(resp.json()["participants"]) == 1


# --- Adding items ------------------------------------------------------------


def test_host_and_guest_items_both_land_in_the_shared_cart_with_correct_adder(
    client,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])

    assert _add(client, customer_token, item, session["id"]).status_code == 200
    assert _add(client, customer2_token, item, session["id"]).status_code == 200

    detail = client.get(
        f"/api/v1/cart/group-sessions/{session['id']}",
        headers=_auth_headers(customer_token),
    ).json()
    adders = {i["added_by_name"] for i in detail["cart"]["items"]}
    assert adders == {"A Customer", "Another Customer"}
    assert len(detail["cart"]["items"]) == 2  # not merged into one line


def test_non_participant_cannot_add_to_the_session(
    client,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    """customer2 never joined — add_item must reject them, not silently
    let anyone with a session_id add to someone else's cart."""
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    resp = _add(client, customer2_token, item, session["id"])
    assert resp.status_code == 403


def test_spending_cap_blocks_guest_but_not_host(
    client,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item  # price 150.00
    session = _start(client, customer_token, per_person_limit="100.00")
    _join(client, customer2_token, session["join_code"])

    guest_resp = _add(client, customer2_token, item, session["id"])
    assert guest_resp.status_code == 409

    host_resp = _add(client, customer_token, item, session["id"])
    assert host_resp.status_code == 200, host_resp.text


# --- Leaving / removal --------------------------------------------------------


def test_guest_can_leave_and_their_items_are_removed(
    client,
    db_session,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    _add(client, customer2_token, item, session["id"])

    resp = client.delete(
        f"/api/v1/cart/group-sessions/{session['id']}/leave",
        headers=_auth_headers(customer2_token),
    )
    assert resp.status_code == 200, resp.text

    remaining_items = db_session.query(CartItem).count()
    assert remaining_items == 0


def test_host_cannot_leave(client, customer_token):  # noqa: F811
    session = _start(client, customer_token)
    resp = client.delete(
        f"/api/v1/cart/group-sessions/{session['id']}/leave",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409


def test_host_can_remove_a_participant(
    client,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    _add(client, customer2_token, item, session["id"])

    resp = client.delete(
        f"/api/v1/cart/group-sessions/{session['id']}/participants/"
        f"{_user_id(client, customer2_token)}",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text

    detail = client.get(
        f"/api/v1/cart/group-sessions/{session['id']}",
        headers=_auth_headers(customer_token),
    ).json()
    assert detail["participants"] == []
    assert detail["cart"]["items"] == []


# --- Cancel -------------------------------------------------------------------


def test_cancel_only_works_while_open(
    client,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _add(client, customer_token, item, session["id"])
    lock_resp = _lock(client, customer_token, session["id"])
    assert lock_resp.status_code == 200, lock_resp.text

    resp = client.post(
        f"/api/v1/cart/group-sessions/{session['id']}/cancel",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409


# --- Lock / checkout split -----------------------------------------------------


def test_lock_splits_cart_into_one_order_per_payer_host_covers_fees(
    client,
    db_session,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item  # price 150.00
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    _add(client, customer_token, item, session["id"])  # host: 150.00
    _add(client, customer2_token, item, session["id"])  # guest: 150.00

    resp = _lock(client, customer_token, session["id"])
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["session"]["status"] == "locked"
    assert len(body["payers"]) == 2

    host_payer = next(p for p in body["payers"] if p["is_host"])
    guest_payer = next(p for p in body["payers"] if not p["is_host"])

    host_order = (
        db_session.query(Order)
        .filter(Order.id == uuid.UUID(host_payer["order_id"]))
        .first()
    )
    guest_order = (
        db_session.query(Order)
        .filter(Order.id == uuid.UUID(guest_payer["order_id"]))
        .first()
    )

    assert host_order.subtotal == guest_order.subtotal == Decimal("150.00")
    # Combined subtotal 300.00 -> host's service_fee/vat computed on
    # that, not just their own 150.00 -- guest's are exactly zero.
    assert guest_order.service_fee == Decimal("0.00")
    assert guest_order.vat == Decimal("0.00")
    assert host_order.service_fee > Decimal("0.00")
    assert host_order.status == OrderStatus.PENDING_PAYMENT.value
    assert guest_order.status == OrderStatus.PENDING_PAYMENT.value

    # Cart is cleared, same as a normal solo checkout.
    remaining = db_session.query(CartItem).count()
    assert remaining == 0


def test_lock_requires_at_least_one_item(client, customer_token):  # noqa: F811
    session = _start(client, customer_token)
    resp = _lock(client, customer_token, session["id"])
    assert resp.status_code == 400


def test_only_host_can_lock(
    client,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    _add(client, customer_token, item, session["id"])
    resp = _lock(client, customer2_token, session["id"])
    assert resp.status_code == 403


# --- Webhook coordination across sibling orders -------------------------------


def test_branch_notified_only_once_all_sibling_orders_are_paid(
    client,
    db_session,
    monkeypatch,
    customer_token,  # noqa: F811
    customer2_token,  # noqa: F811
    branch_and_item,  # noqa: F811
):
    from app.core.config import settings
    from app.services import dispatch as dispatch_service
    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"}
    )
    dispatch_calls = []
    monkeypatch.setattr(
        dispatch_service,
        "dispatch_next_courier",
        lambda db, redis, order: dispatch_calls.append(order.id),
    )

    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    _add(client, customer_token, item, session["id"])
    _add(client, customer2_token, item, session["id"])
    lock_body = _lock(
        client,
        customer_token,
        session["id"],
        delivery_mode="delivery",
        delivery_address="Bole",
        delivery_latitude=9.006,
        delivery_longitude=38.764,
    ).json()

    host_payer = next(p for p in lock_body["payers"] if p["is_host"])
    guest_payer = next(p for p in lock_body["payers"] if not p["is_host"])
    host_order = (
        db_session.query(Order)
        .filter(Order.id == uuid.UUID(host_payer["order_id"]))
        .first()
    )
    guest_order = (
        db_session.query(Order)
        .filter(Order.id == uuid.UUID(guest_payer["order_id"]))
        .first()
    )

    # Guest pays first -- dispatch must NOT fire yet, host still unpaid.
    raw, sig = _sign({"tx_ref": guest_order.tx_ref, "event": "charge.success"})
    resp = _post_webhook(client, raw, sig)
    assert resp.status_code == 200
    assert dispatch_calls == []

    # Host pays -- NOW the whole group is settled, dispatch fires once,
    # on the host's order specifically.
    raw, sig = _sign({"tx_ref": host_order.tx_ref, "event": "charge.success"})
    resp = _post_webhook(client, raw, sig)
    assert resp.status_code == 200
    assert dispatch_calls == [host_order.id]


# --- Finalize / absorb unpaid guest items --------------------------------------


def test_finalize_absorbs_unpaid_guest_items_when_host_also_unpaid(
    client,
    db_session,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    _add(client, customer_token, item, session["id"])
    _add(client, customer2_token, item, session["id"])
    lock_body = _lock(client, customer_token, session["id"]).json()
    host_payer = next(p for p in lock_body["payers"] if p["is_host"])
    original_host_total = Decimal(host_payer["amount"])

    resp = client.post(
        f"/api/v1/cart/group-sessions/{session['id']}/finalize",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["session"]["status"] == "checked_out"
    assert len(body["payers"]) == 1  # guest's order was cancelled, absorbed

    host_order = (
        db_session.query(Order)
        .filter(Order.id == uuid.UUID(host_payer["order_id"]))
        .first()
    )
    db_session.refresh(host_order)
    assert host_order.total > original_host_total


def test_finalize_does_not_absorb_once_host_already_paid(
    client,
    db_session,
    customer_token,
    customer2_token,
    branch_and_item,  # noqa: F811
):
    """If the host already paid their own (smaller) total, the amount
    Chapa actually collected can't be silently grown -- the unpaid
    guest's order is just cancelled, not merged in."""
    _branch, item = branch_and_item
    session = _start(client, customer_token)
    _join(client, customer2_token, session["join_code"])
    _add(client, customer_token, item, session["id"])
    _add(client, customer2_token, item, session["id"])
    lock_body = _lock(client, customer_token, session["id"]).json()
    host_payer = next(p for p in lock_body["payers"] if p["is_host"])
    host_order_id = uuid.UUID(host_payer["order_id"])

    host_order = db_session.query(Order).filter(Order.id == host_order_id).first()
    host_order.payment_status = PaymentStatus.PAID.value
    original_total = host_order.total
    db_session.commit()

    resp = client.post(
        f"/api/v1/cart/group-sessions/{session['id']}/finalize",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text

    db_session.refresh(host_order)
    assert host_order.total == original_total  # unchanged, nothing absorbed
