import uuid
from datetime import timedelta

import pytest

from app.core import security
from app.models.promo_code import DiscountType, PromoCode
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone
from app.utils.time import utcnow

SUPPLIER_PHONE = "0963000001"
SUPPLIER2_PHONE = "0963000002"
ADMIN_PHONE = "0963000003"
CUSTOMER_PHONE = "0963000004"
CUSTOMER2_PHONE = "0963000005"
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(db_session):
    return _seed_user(
        db_session, SUPPLIER2_PHONE, "Another Supplier", UserRole.SUPPLIER
    )


@pytest.fixture()
def supplier2_token(client, supplier2):
    return _login(client, SUPPLIER2_PHONE)


@pytest.fixture()
def admin(db_session):
    return _seed_user(db_session, ADMIN_PHONE, "An Admin", UserRole.ADMIN)


@pytest.fixture()
def admin_token(client, 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)


def _make_merchant_branch_item(client, supplier_token, admin_token, price="150.00"):
    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": price},
        headers=_auth_headers(supplier_token),
    ).json()
    return merchant, branch, item


@pytest.fixture()
def merchant_branch_item(client, supplier_token, admin_token):
    return _make_merchant_branch_item(client, supplier_token, admin_token)


def _add_branch_and_item(
    client,
    supplier_token,
    admin_token,
    merchant_id,
    name="Second Branch",
    price="150.00",
):
    branch = client.post(
        f"/api/v1/merchants/{merchant_id}/branches",
        json={
            "name": name,
            "address": "Piassa, Addis Ababa",
            "latitude": 9.035,
            "longitude": 38.749,
            "phone": "0911998877",
        },
        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": price},
        headers=_auth_headers(supplier_token),
    ).json()
    return branch, item


def _add_to_cart(client, token, item, quantity=1):
    return client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": quantity},
        headers=_auth_headers(token),
    )


def _checkout(client, token, promo_code=None):
    payload = {"delivery_mode": "takeaway", "payment_method": "cash"}
    if promo_code is not None:
        payload["promo_code"] = promo_code
    return client.post(
        "/api/v1/orders/checkout", json=payload, headers=_auth_headers(token)
    )


# --- Minimum order amount ------------------------------------------------


def test_update_minimum_order_requires_authentication(client, merchant_branch_item):
    _merchant, branch, _item = merchant_branch_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/minimum-order",
        json={"minimum_order_amount": "200.00"},
    )
    assert resp.status_code == 401  # no Authorization header at all


def test_update_minimum_order_rejects_non_staff(
    client, merchant_branch_item, supplier2_token
):
    _merchant, branch, _item = merchant_branch_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/minimum-order",
        json={"minimum_order_amount": "200.00"},
        headers=_auth_headers(supplier2_token),
    )
    assert resp.status_code == 403


def test_update_minimum_order_allows_owner(
    client, merchant_branch_item, supplier_token
):
    _merchant, branch, _item = merchant_branch_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/minimum-order",
        json={"minimum_order_amount": "200.00"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["minimum_order_amount"] == "200.00"


def test_update_minimum_order_rejects_negative(
    client, merchant_branch_item, supplier_token
):
    _merchant, branch, _item = merchant_branch_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/minimum-order",
        json={"minimum_order_amount": "-10.00"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 422


def test_checkout_blocks_below_minimum_order_amount(
    client, merchant_branch_item, supplier_token, customer_token
):
    _merchant, branch, item = merchant_branch_item
    client.patch(
        f"/api/v1/branches/{branch['id']}/minimum-order",
        json={"minimum_order_amount": "200.00"},
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)  # subtotal 150.00

    resp = _checkout(client, customer_token)
    assert resp.status_code == 422
    assert "minimum order" in resp.json()["detail"].lower()


def test_checkout_allows_at_minimum_order_amount(
    client, merchant_branch_item, supplier_token, customer_token
):
    _merchant, branch, item = merchant_branch_item
    client.patch(
        f"/api/v1/branches/{branch['id']}/minimum-order",
        json={"minimum_order_amount": "150.00"},
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)  # subtotal exactly 150.00

    resp = _checkout(client, customer_token)
    assert resp.status_code == 200, resp.text


def test_checkout_unaffected_when_no_minimum_set(
    client, merchant_branch_item, customer_token
):
    _merchant, _branch, item = merchant_branch_item
    _add_to_cart(client, customer_token, item, quantity=1)
    resp = _checkout(client, customer_token)
    assert resp.status_code == 200, resp.text


# --- Promo code CRUD -------------------------------------------------


def test_create_promo_code_rejects_customer(client, customer_token):
    resp = client.post(
        "/api/v1/promo-codes",
        json={"code": "SAVE10", "discount_type": "percentage", "discount_value": "10"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 403


def test_create_promo_code_admin_platform_wide(client, admin_token):
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "WELCOME10",
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["merchant_id"] is None
    assert body["code"] == "WELCOME10"


def test_create_promo_code_supplier_requires_merchant_id(client, supplier_token):
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "SUPPLIER5",
            "discount_type": "percentage",
            "discount_value": "5",
        },
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 422


def test_create_promo_code_supplier_own_merchant(
    client, supplier_token, merchant_branch_item
):
    merchant, _branch, _item = merchant_branch_item
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "BURGER10",
            "merchant_id": merchant["id"],
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["merchant_id"] == merchant["id"]


def test_create_promo_code_supplier_rejects_other_merchant(
    client, supplier2_token, merchant_branch_item
):
    merchant, _branch, _item = merchant_branch_item
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "STEAL10",
            "merchant_id": merchant["id"],
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(supplier2_token),
    )
    assert resp.status_code == 403


def test_create_promo_code_rejects_duplicate_code(client, admin_token):
    payload = {"code": "DUPE10", "discount_type": "percentage", "discount_value": "10"}
    client.post("/api/v1/promo-codes", json=payload, headers=_auth_headers(admin_token))
    resp = client.post(
        "/api/v1/promo-codes", json=payload, headers=_auth_headers(admin_token)
    )
    assert resp.status_code == 409


def test_create_promo_code_rejects_percentage_over_100(client, admin_token):
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "TOOMUCH",
            "discount_type": "percentage",
            "discount_value": "150",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_create_promo_code_rejects_max_discount_on_fixed_amount(client, admin_token):
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "FIXEDBAD",
            "discount_type": "fixed_amount",
            "discount_value": "20",
            "max_discount_amount": "10",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_list_promo_codes_supplier_sees_only_own(
    client, admin_token, supplier_token, merchant_branch_item
):
    merchant, _branch, _item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "PLATFORMWIDE",
            "discount_type": "percentage",
            "discount_value": "5",
        },
        headers=_auth_headers(admin_token),
    )
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "MYOWN",
            "merchant_id": merchant["id"],
            "discount_type": "percentage",
            "discount_value": "5",
        },
        headers=_auth_headers(supplier_token),
    )

    resp = client.get("/api/v1/promo-codes", headers=_auth_headers(supplier_token))
    assert resp.status_code == 200
    codes = [p["code"] for p in resp.json()]
    assert codes == ["MYOWN"]


def test_list_promo_codes_admin_sees_all(
    client, admin_token, supplier_token, merchant_branch_item
):
    merchant, _branch, _item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "PLATFORMWIDE2",
            "discount_type": "percentage",
            "discount_value": "5",
        },
        headers=_auth_headers(admin_token),
    )
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "MYOWN2",
            "merchant_id": merchant["id"],
            "discount_type": "percentage",
            "discount_value": "5",
        },
        headers=_auth_headers(supplier_token),
    )

    resp = client.get("/api/v1/promo-codes", headers=_auth_headers(admin_token))
    assert resp.status_code == 200
    assert len(resp.json()) == 2


def test_update_promo_code_toggle_is_active(client, admin_token):
    created = client.post(
        "/api/v1/promo-codes",
        json={"code": "TOGGLEME", "discount_type": "percentage", "discount_value": "5"},
        headers=_auth_headers(admin_token),
    ).json()
    resp = client.patch(
        f"/api/v1/promo-codes/{created['id']}",
        json={"is_active": False},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["is_active"] is False


def test_update_promo_code_supplier_cannot_touch_platform_wide(
    client, admin_token, supplier_token
):
    created = client.post(
        "/api/v1/promo-codes",
        json={"code": "NOTOUCH", "discount_type": "percentage", "discount_value": "5"},
        headers=_auth_headers(admin_token),
    ).json()
    resp = client.patch(
        f"/api/v1/promo-codes/{created['id']}",
        json={"is_active": False},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 403


# --- Checkout with a promo code ---------------------------------------


def test_checkout_merchant_funded_discount_leaves_service_fee_untouched(
    client, merchant_branch_item, supplier_token, customer_token
):
    """A merchant-created code comes off the merchant's own share
    (subtotal) — Yeneb's service_fee, its only revenue on an order,
    stays at its full value. VAT follows the discounted price, since
    that's what's actually being sold (matches the legacy system's own
    VAT-on-post-discount-price treatment)."""
    merchant, _branch, item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "PCT10",
            "merchant_id": merchant["id"],
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)  # subtotal 150.00

    resp = _checkout(client, customer_token, promo_code="pct10")  # lowercase on purpose
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["discount_amount"] == "15.00"  # 10% of 150
    assert body["promo_code_id"] is not None
    assert body["service_fee"] == "7.50"  # full 5% of 150, untouched
    assert body["vat"] == "20.25"  # 15% of (150 - 15 discount)
    # subtotal 150 + service_fee 7.50 + vat 20.25 - discount 15.00
    assert body["total"] == "162.75"


def test_checkout_merchant_funded_fixed_amount_discount(
    client, merchant_branch_item, supplier_token, customer_token
):
    merchant, _branch, item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "FLAT20",
            "merchant_id": merchant["id"],
            "discount_type": "fixed_amount",
            "discount_value": "20",
        },
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="FLAT20")
    assert resp.status_code == 200, resp.text
    assert resp.json()["discount_amount"] == "20.00"


def test_checkout_merchant_funded_discount_capped_by_max_discount_amount(
    client, merchant_branch_item, supplier_token, customer_token
):
    merchant, _branch, item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "CAPPED",
            "merchant_id": merchant["id"],
            "discount_type": "percentage",
            "discount_value": "50",
            "max_discount_amount": "10",
        },
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(
        client, customer_token, item, quantity=1
    )  # 50% of 150 = 75, capped to 10

    resp = _checkout(client, customer_token, promo_code="CAPPED")
    assert resp.status_code == 200, resp.text
    assert resp.json()["discount_amount"] == "10.00"


def test_checkout_platform_funded_discount_comes_off_service_fee(
    client, merchant_branch_item, admin_token, customer_token
):
    """A platform-wide (admin-created, no merchant_id) code is funded
    by Yeneb itself, not the merchant — it comes off service_fee
    (Yeneb's only revenue on an order), never off subtotal, so the
    merchant is always paid their full, undiscounted share and VAT
    (which never taxes service_fee) is unaffected."""
    _merchant, _branch, item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "SPONSORED",
            "discount_type": "fixed_amount",
            "discount_value": "3",
        },
        headers=_auth_headers(admin_token),
    )
    _add_to_cart(
        client, customer_token, item, quantity=1
    )  # subtotal 150.00, service_fee 7.50

    resp = _checkout(client, customer_token, promo_code="SPONSORED")
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["discount_amount"] == "3.00"
    assert body["subtotal"] == "150.00"  # merchant's share untouched
    assert body["vat"] == "22.50"  # 15% of the full, undiscounted subtotal
    # subtotal 150 + service_fee 7.50 + vat 22.50 - discount 3.00
    assert body["total"] == "177.00"


def test_checkout_platform_funded_discount_capped_at_service_fee(
    client, merchant_branch_item, admin_token, customer_token
):
    """However generous the code, a platform-funded discount can never
    exceed what Yeneb itself earns on the order (service_fee) — it
    must never eat into the merchant's own share."""
    _merchant, _branch, item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "TOOGENEROUS",
            "discount_type": "percentage",
            "discount_value": "50",
        },
        headers=_auth_headers(admin_token),
    )
    _add_to_cart(
        client, customer_token, item, quantity=1
    )  # 50% of 150 = 75, but service_fee is only 7.50

    resp = _checkout(client, customer_token, promo_code="TOOGENEROUS")
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["discount_amount"] == "7.50"  # capped at service_fee, not 75.00
    assert body["subtotal"] == "150.00"
    assert body["total"] == "172.50"  # 150 + 7.50 + 22.50 - 7.50


def test_checkout_rejects_invalid_promo_code(
    client, merchant_branch_item, customer_token
):
    _merchant, _branch, item = merchant_branch_item
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="DOESNOTEXIST")
    assert resp.status_code == 422
    assert "invalid" in resp.json()["detail"].lower()


def test_checkout_rejects_inactive_promo_code(
    client, merchant_branch_item, admin_token, customer_token
):
    _merchant, _branch, item = merchant_branch_item
    created = client.post(
        "/api/v1/promo-codes",
        json={"code": "OFFNOW", "discount_type": "percentage", "discount_value": "10"},
        headers=_auth_headers(admin_token),
    ).json()
    client.patch(
        f"/api/v1/promo-codes/{created['id']}",
        json={"is_active": False},
        headers=_auth_headers(admin_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="OFFNOW")
    assert resp.status_code == 422


def test_checkout_rejects_promo_code_below_min_order_amount(
    client, merchant_branch_item, admin_token, customer_token
):
    _merchant, _branch, item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "BIGORDER",
            "discount_type": "percentage",
            "discount_value": "10",
            "min_order_amount": "500.00",
        },
        headers=_auth_headers(admin_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)  # subtotal only 150

    resp = _checkout(client, customer_token, promo_code="BIGORDER")
    assert resp.status_code == 422
    assert "minimum order" in resp.json()["detail"].lower()


def test_checkout_rejects_promo_code_for_different_merchant(
    client, supplier_token, supplier2_token, admin_token, customer_token
):
    _merchant, _branch, item = _make_merchant_branch_item(
        client, supplier_token, admin_token
    )
    other_merchant, _other_branch, _other_item = _make_merchant_branch_item(
        client, supplier2_token, admin_token, price="99.00"
    )
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "OTHERSTORE",
            "merchant_id": other_merchant["id"],
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(supplier2_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="OTHERSTORE")
    assert resp.status_code == 422
    assert "isn't valid" in resp.json()["detail"].lower()


def test_checkout_rejects_expired_promo_code(
    client, db_session, merchant_branch_item, admin, customer_token
):
    _merchant, _branch, item = merchant_branch_item
    promo = PromoCode(
        code="EXPIRED",
        created_by_id=admin.id,
        discount_type=DiscountType.PERCENTAGE.value,
        discount_value=10,
        valid_until=utcnow() - timedelta(days=1),
    )
    db_session.add(promo)
    db_session.commit()
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="EXPIRED")
    assert resp.status_code == 422
    assert "expired" in resp.json()["detail"].lower()


def test_checkout_rejects_promo_code_not_yet_valid(
    client, db_session, merchant_branch_item, admin, customer_token
):
    _merchant, _branch, item = merchant_branch_item
    promo = PromoCode(
        code="TOOSOON",
        created_by_id=admin.id,
        discount_type=DiscountType.PERCENTAGE.value,
        discount_value=10,
        valid_from=utcnow() + timedelta(days=1),
    )
    db_session.add(promo)
    db_session.commit()
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="TOOSOON")
    assert resp.status_code == 422
    assert "isn't active yet" in resp.json()["detail"].lower()


def test_checkout_rejects_promo_code_usage_limit_reached(
    client, db_session, merchant_branch_item, admin, customer_token, customer2_token
):
    _merchant, _branch, item = merchant_branch_item
    promo = PromoCode(
        code="ONLYONE",
        created_by_id=admin.id,
        discount_type=DiscountType.PERCENTAGE.value,
        discount_value=10,
        usage_limit=1,
    )
    db_session.add(promo)
    db_session.commit()

    _add_to_cart(client, customer_token, item, quantity=1)
    first = _checkout(client, customer_token, promo_code="ONLYONE")
    assert first.status_code == 200, first.text

    _add_to_cart(client, customer2_token, item, quantity=1)
    second = _checkout(client, customer2_token, promo_code="ONLYONE")
    assert second.status_code == 422
    assert "usage limit" in second.json()["detail"].lower()


def test_checkout_rejects_promo_code_per_customer_limit_reached(
    client, db_session, merchant_branch_item, admin, customer_token
):
    _merchant, _branch, item = merchant_branch_item
    promo = PromoCode(
        code="ONCEEACH",
        created_by_id=admin.id,
        discount_type=DiscountType.PERCENTAGE.value,
        discount_value=10,
        usage_limit_per_customer=1,
    )
    db_session.add(promo)
    db_session.commit()

    _add_to_cart(client, customer_token, item, quantity=1)
    first = _checkout(client, customer_token, promo_code="ONCEEACH")
    assert first.status_code == 200, first.text

    _add_to_cart(client, customer_token, item, quantity=1)
    second = _checkout(client, customer_token, promo_code="ONCEEACH")
    assert second.status_code == 422
    assert "already used" in second.json()["detail"].lower()


def test_checkout_redemption_creates_record_and_increments_times_used(
    client, db_session, merchant_branch_item, supplier_token, customer_token
):
    from app.models.promo_code import PromoCodeRedemption

    merchant, _branch, item = merchant_branch_item
    created = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "TRACKME",
            "merchant_id": merchant["id"],
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(supplier_token),
    ).json()
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="TRACKME")
    assert resp.status_code == 200, resp.text
    order_id = resp.json()["id"]

    import uuid as uuid_module

    redemption = (
        db_session.query(PromoCodeRedemption)
        .filter(PromoCodeRedemption.order_id == uuid_module.UUID(order_id))
        .first()
    )
    assert redemption is not None
    assert redemption.discount_amount == pytest.approx(15.00)

    promo = (
        db_session.query(PromoCode)
        .filter(PromoCode.id == uuid_module.UUID(created["id"]))
        .first()
    )
    assert promo.times_used == 1


# --- Branch-scoped promo codes -----------------------------------------


def test_create_promo_code_rejects_branch_id_without_merchant_id(client, admin_token):
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "NOBRANCH",
            "branch_id": str(uuid.uuid4()),
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_create_promo_code_rejects_branch_from_a_different_merchant(
    client, admin_token, supplier2_token, merchant_branch_item
):
    merchant, _branch, _item = merchant_branch_item
    other_merchant = client.post(
        "/api/v1/merchants",
        json={"name": "Someone Else's Place"},
        headers=_auth_headers(supplier2_token),
    ).json()

    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "MISMATCHED",
            "merchant_id": other_merchant["id"],
            "branch_id": merchant["id"],  # not even a branch, let alone the right one
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_create_promo_code_supplier_scopes_to_own_branch(
    client, supplier_token, admin_token, merchant_branch_item
):
    merchant, branch, _item = merchant_branch_item
    resp = client.post(
        "/api/v1/promo-codes",
        json={
            "code": "BRANCHONLY",
            "merchant_id": merchant["id"],
            "branch_id": branch["id"],
            "discount_type": "percentage",
            "discount_value": "10",
        },
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["branch_id"] == branch["id"]


def test_checkout_branch_scoped_code_works_at_its_own_branch(
    client, supplier_token, admin_token, merchant_branch_item, customer_token
):
    merchant, branch, item = merchant_branch_item
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "THISBRANCH",
            "merchant_id": merchant["id"],
            "branch_id": branch["id"],
            "discount_type": "fixed_amount",
            "discount_value": "5",
        },
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="THISBRANCH")
    assert resp.status_code == 200, resp.text
    assert resp.json()["discount_amount"] == "5.00"


def test_checkout_branch_scoped_code_rejected_at_a_different_branch_of_the_same_merchant(
    client, supplier_token, admin_token, merchant_branch_item, customer_token
):
    merchant, branch, _item = merchant_branch_item
    _second_branch, second_item = _add_branch_and_item(
        client, supplier_token, admin_token, merchant["id"]
    )
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "FIRSTBRANCHONLY",
            "merchant_id": merchant["id"],
            "branch_id": branch["id"],
            "discount_type": "fixed_amount",
            "discount_value": "5",
        },
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(client, customer_token, second_item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="FIRSTBRANCHONLY")
    assert resp.status_code == 422
    assert "isn't valid for this branch" in resp.json()["detail"].lower()


def test_checkout_merchant_wide_code_works_at_every_branch(
    client, supplier_token, admin_token, merchant_branch_item, customer_token
):
    """No branch_id set — the code works at any of the merchant's
    branches, not just the one it happened to be tested against
    first."""
    merchant, _branch, _item = merchant_branch_item
    second_branch, second_item = _add_branch_and_item(
        client, supplier_token, admin_token, merchant["id"]
    )
    client.post(
        "/api/v1/promo-codes",
        json={
            "code": "ALLBRANCHES",
            "merchant_id": merchant["id"],
            "discount_type": "fixed_amount",
            "discount_value": "5",
        },
        headers=_auth_headers(supplier_token),
    )
    _add_to_cart(client, customer_token, second_item, quantity=1)

    resp = _checkout(client, customer_token, promo_code="ALLBRANCHES")
    assert resp.status_code == 200, resp.text
    assert resp.json()["discount_amount"] == "5.00"
