import uuid

import pytest

from app.core import security
from app.core.config import settings
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0959000001"
SUPPLIER2_PHONE = "0959000002"
ADMIN_PHONE = "0959000003"
CUSTOMER_PHONE = "0959000004"
CUSTOMER2_PHONE = "0959000005"
SEED_PIN = "111111"


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 supplier2_token(client, db_session):
    _seed_user(db_session, SUPPLIER2_PHONE, "Another Supplier", UserRole.SUPPLIER)
    return _login(client, SUPPLIER2_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 customer2_token(client, db_session):
    _seed_user(db_session, CUSTOMER2_PHONE, "Another Customer", UserRole.CUSTOMER)
    return _login(client, CUSTOMER2_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 _add_to_cart(
    client, token, item, quantity=1, option_ids=None, special_instructions=None
):
    payload = {"menu_item_id": item["id"], "quantity": quantity}
    if option_ids is not None:
        payload["option_ids"] = option_ids
    if special_instructions is not None:
        payload["special_instructions"] = special_instructions
    return client.post("/api/v1/cart/items", json=payload, headers=_auth_headers(token))


def _create_group(client, token, branch_id, item_id, **overrides):
    payload = {"name": "Add-ons", "selection_type": "multiple", "is_required": False}
    payload.update(overrides)
    return client.post(
        f"/api/v1/branches/{branch_id}/items/{item_id}/option-groups",
        json=payload,
        headers=_auth_headers(token),
    ).json()


def _create_option(client, token, branch_id, item_id, group_id, **overrides):
    payload = {"name": "Extra Cheese", "price_delta": "15.00"}
    payload.update(overrides)
    return client.post(
        f"/api/v1/branches/{branch_id}/items/{item_id}/option-groups/{group_id}/options",
        json=payload,
        headers=_auth_headers(token),
    ).json()


def _checkout(client, token, delivery_mode="takeaway", delivery_address=None):
    payload = {"delivery_mode": delivery_mode}
    if delivery_address is not None:
        payload["delivery_address"] = delivery_address
    return client.post(
        "/api/v1/orders/checkout", json=payload, headers=_auth_headers(token)
    )


# --- Checkout --------------------------------------------------------


def test_checkout_rejects_empty_cart(client, customer_token):
    resp = _checkout(client, customer_token)
    assert resp.status_code == 400


def test_checkout_requires_customer_role(client, supplier_token):
    resp = _checkout(client, supplier_token)
    assert resp.status_code == 403


def test_checkout_is_rate_limited_per_user(client, customer_token):
    """The rate limit is checked before the empty-cart check (see
    app.api.v1.endpoints.orders.checkout), so repeated attempts with an
    empty cart are enough to trip it without any real checkout going
    through."""
    limit = settings.checkout_rate_limit_max_attempts
    for _ in range(limit):
        resp = _checkout(client, customer_token)
        assert resp.status_code == 400  # empty cart, but not rate limited yet

    tripped = _checkout(client, customer_token)
    assert tripped.status_code == 429
    assert "Retry-After" in tripped.headers


def test_checkout_requires_address_for_delivery(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 2)

    resp = _checkout(client, customer_token, delivery_mode="delivery")
    assert resp.status_code == 422


def test_checkout_creates_order_and_clears_cart(
    client, customer_token, branch_and_item
):
    branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 2)

    resp = _checkout(client, customer_token)
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["branch_id"] == branch["id"]
    assert body["status"] == "pending_payment"
    assert body["payment_status"] == "pending"
    assert body["subtotal"] == "300.00"
    assert body["delivery_fee"] == "0.00"  # takeaway
    assert body["service_fee"] == "15.00"  # 5% of subtotal
    assert body["vat"] == "45.00"  # 15% of (subtotal + delivery_fee)
    assert body["total"] == "360.00"
    assert len(body["items"]) == 1
    assert body["items"][0]["name_snapshot"] == "Beef Burger"
    assert body["items"][0]["quantity"] == "2.000"
    assert body["tx_ref"].startswith("yeneb-")
    # chapa_checkout_url is None in tests — Chapa isn't configured, so
    # app.services.payments.chapa.initialize_payment stays log-only (same
    # pattern as SMS/email).
    assert body["chapa_checkout_url"] is None

    cart_resp = client.get("/api/v1/cart", headers=_auth_headers(customer_token))
    assert cart_resp.json()["items"] == []


def test_checkout_rejects_item_that_became_unavailable_after_adding_to_cart(
    client, db_session, customer_token, branch_and_item
):
    """No PATCH endpoint exists yet to toggle availability via the API
    (a known gap), so this flips it directly in the DB to simulate the
    owner marking the item unavailable after it was already in the
    customer's cart — checkout must re-check current availability, not
    just trust what was true when the item was added."""
    from app.models.menu import MenuItem

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)

    db_item = (
        db_session.query(MenuItem).filter(MenuItem.id == uuid.UUID(item["id"])).first()
    )
    db_item.is_available = False
    db_session.commit()

    resp = _checkout(client, customer_token)
    assert resp.status_code == 409


def test_checkout_snapshots_options_and_instructions(
    client, supplier_token, customer_token, branch_and_item
):
    branch, item = branch_and_item
    group = _create_group(client, supplier_token, branch["id"], item["id"])
    option = _create_option(
        client, supplier_token, branch["id"], item["id"], group["id"]
    )
    _add_to_cart(
        client,
        customer_token,
        item,
        quantity=2,
        option_ids=[option["id"]],
        special_instructions="extra crispy",
    )

    resp = _checkout(client, customer_token)
    assert resp.status_code == 200, resp.text
    body = resp.json()
    line = body["items"][0]
    assert line["special_instructions"] == "extra crispy"
    assert len(line["options"]) == 1
    assert line["options"][0]["name_snapshot"] == "Extra Cheese"
    assert line["options"][0]["price_delta_snapshot"] == "15.00"
    # (150.00 + 15.00) * 2
    assert line["line_total"] == "330.00"
    assert body["subtotal"] == "330.00"
    assert body["delivery_fee"] == "0.00"  # takeaway
    assert body["service_fee"] == "16.50"  # 5% of subtotal
    assert body["vat"] == "49.50"  # 15% of (subtotal + delivery_fee)
    assert body["total"] == "396.00"


def test_checkout_rejects_option_that_became_unavailable_after_adding_to_cart(
    client, supplier_token, customer_token, db_session, branch_and_item
):
    import uuid

    from app.models.menu_option import MenuItemOption

    branch, item = branch_and_item
    group = _create_group(client, supplier_token, branch["id"], item["id"])
    option = _create_option(
        client, supplier_token, branch["id"], item["id"], group["id"]
    )
    _add_to_cart(client, customer_token, item, quantity=1, option_ids=[option["id"]])

    db_option = (
        db_session.query(MenuItemOption)
        .filter(MenuItemOption.id == uuid.UUID(option["id"]))
        .first()
    )
    db_option.is_available = False
    db_session.commit()

    resp = _checkout(client, customer_token)
    assert resp.status_code == 409


# --- Visibility --------------------------------------------------------


def test_list_orders_customer_sees_only_their_own(
    client, customer_token, customer2_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    _checkout(client, customer_token)

    resp = client.get("/api/v1/orders", headers=_auth_headers(customer2_token))
    assert resp.status_code == 200
    assert resp.json() == []

    resp = client.get("/api/v1/orders", headers=_auth_headers(customer_token))
    assert resp.status_code == 200
    assert len(resp.json()) == 1


def test_list_orders_supplier_sees_their_branch_orders(
    client, supplier_token, supplier2_token, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    _checkout(client, customer_token)

    resp = client.get("/api/v1/orders", headers=_auth_headers(supplier_token))
    assert resp.status_code == 200
    assert len(resp.json()) == 1

    resp = client.get("/api/v1/orders", headers=_auth_headers(supplier2_token))
    assert resp.status_code == 200
    assert resp.json() == []


def test_get_order_404s_for_unrelated_customer(
    client, customer_token, customer2_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    order = _checkout(client, customer_token).json()

    resp = client.get(
        f"/api/v1/orders/{order['id']}", headers=_auth_headers(customer2_token)
    )
    assert resp.status_code == 404


def test_get_order_visible_to_owning_supplier(
    client, supplier_token, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    order = _checkout(client, customer_token).json()

    resp = client.get(
        f"/api/v1/orders/{order['id']}", headers=_auth_headers(supplier_token)
    )
    assert resp.status_code == 200


# --- Status transitions --------------------------------------------------


def test_update_status_rejects_before_payment(
    client, supplier_token, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    order = _checkout(client, customer_token).json()

    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "preparing"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 409


def test_update_status_rejects_non_staff(
    client, customer_token, supplier2_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    order = _checkout(client, customer_token).json()

    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "confirmed"},
        headers=_auth_headers(supplier2_token),
    )
    assert resp.status_code == 403


def test_valid_status_progression_after_payment(
    client, db_session, supplier_token, customer_token, branch_and_item
):
    from app.models.order import Order, OrderStatus, PaymentStatus

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    order = _checkout(client, customer_token).json()

    # Simulate a paid webhook having already landed.
    db_order = (
        db_session.query(Order).filter(Order.id == uuid.UUID(order["id"])).first()
    )
    db_order.payment_status = PaymentStatus.PAID.value
    db_order.status = OrderStatus.CONFIRMED.value
    db_session.commit()

    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
    assert resp.json()["status"] == "preparing"

    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "ready"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200
    assert resp.json()["status"] == "ready"

    # Can't skip straight from ready to preparing again.
    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "preparing"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 409

    resp = client.patch(
        f"/api/v1/orders/{order['id']}/status",
        json={"status": "completed"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200
    assert resp.json()["status"] == "completed"


# --- Cancel --------------------------------------------------------------


def test_cancel_order_before_payment(client, customer_token, branch_and_item):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    order = _checkout(client, customer_token).json()

    resp = client.post(
        f"/api/v1/orders/{order['id']}/cancel", headers=_auth_headers(customer_token)
    )
    assert resp.status_code == 200
    assert resp.json()["status"] == "cancelled"


def test_cancel_order_rejected_once_preparing(
    client, db_session, customer_token, branch_and_item
):
    """A customer can still self-cancel a paid, CONFIRMED order (see
    tests/test_cancellation.py) — but once the branch has started
    preparing it, only staff can cancel from there."""
    from app.models.order import Order, OrderStatus, PaymentStatus

    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, 1)
    order = _checkout(client, customer_token).json()

    db_order = (
        db_session.query(Order).filter(Order.id == uuid.UUID(order["id"])).first()
    )
    db_order.payment_status = PaymentStatus.PAID.value
    db_order.status = OrderStatus.PREPARING.value
    db_session.commit()

    resp = client.post(
        f"/api/v1/orders/{order['id']}/cancel", headers=_auth_headers(customer_token)
    )
    assert resp.status_code == 409
