import pytest

from app.core import security
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0962000001"
ADMIN_PHONE = "0962000002"
CUSTOMER_PHONE = "0962000003"
SEED_PIN = "111111"

# Same branch coordinates every fixture in this file uses; the delivery
# point below is a fixed short hop from it, giving a deterministic
# haversine distance (~0.7814 km) so the expected delivery_fee is a
# known constant rather than something computed twice in the test.
BRANCH_LOCATION = {"latitude": 9.005, "longitude": 38.763}
DELIVERY_LOCATION = {"latitude": 9.010, "longitude": 38.768}
# 20.00 base + 0.7814... km * 10.00 per_km, rounded to cents.
EXPECTED_DELIVERY_FEE = "27.81"


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 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",
            **BRANCH_LOCATION,
            "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):
    return client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": quantity},
        headers=_auth_headers(token),
    )


def _checkout_delivery(client, token, **overrides):
    payload = {
        "delivery_mode": "delivery",
        "delivery_address": "Kazanchis, Addis Ababa",
        "delivery_latitude": DELIVERY_LOCATION["latitude"],
        "delivery_longitude": DELIVERY_LOCATION["longitude"],
        "payment_method": "cash",
    }
    payload.update(overrides)
    return client.post(
        "/api/v1/orders/checkout", json=payload, headers=_auth_headers(token)
    )


def test_delivery_checkout_computes_distance_based_fee_and_charges(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=2)  # subtotal 300.00

    resp = _checkout_delivery(client, customer_token)
    assert resp.status_code == 200, resp.text
    body = resp.json()

    assert body["subtotal"] == "300.00"
    assert body["delivery_fee"] == EXPECTED_DELIVERY_FEE
    assert body["vat"] == "49.17"  # (300.00 + 27.81) * 15%
    assert body["service_fee"] == "15.00"  # 5% of subtotal only
    assert body["total"] == "391.98"  # 300.00 + 27.81 + 49.17 + 15.00
    assert body["delivery_latitude"] == DELIVERY_LOCATION["latitude"]
    assert body["delivery_longitude"] == DELIVERY_LOCATION["longitude"]


def test_takeaway_checkout_has_zero_delivery_fee(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)  # subtotal 150.00

    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
    body = resp.json()
    assert body["delivery_fee"] == "0.00"
    assert body["delivery_latitude"] is None
    assert body["delivery_longitude"] is None
    # service_fee/vat still apply — a platform charge, not a delivery cost.
    assert body["service_fee"] == "7.50"
    assert body["vat"] == "22.50"
    assert body["total"] == "180.00"  # 150 + 0 + 22.50 + 7.50


def test_delivery_checkout_requires_coordinates(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = client.post(
        "/api/v1/orders/checkout",
        json={
            "delivery_mode": "delivery",
            "delivery_address": "Kazanchis, Addis Ababa",
            "payment_method": "cash",
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 422


def test_delivery_checkout_rejects_out_of_range_latitude(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout_delivery(client, customer_token, delivery_latitude=95.0)
    assert resp.status_code == 422


def test_delivery_checkout_rejects_out_of_range_longitude(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _checkout_delivery(client, customer_token, delivery_longitude=200.0)
    assert resp.status_code == 422
