import uuid

import pytest

from app.core import security
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0959000001"
ADMIN_PHONE = "0959000002"
CUSTOMER_PHONE = "0959000003"
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 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)


def _create_merchant(client, supplier_token, business_type=None, name="Fresh Mart"):
    payload = {"name": name}
    if business_type is not None:
        payload["business_type"] = business_type
    resp = client.post(
        "/api/v1/merchants", json=payload, headers=_auth_headers(supplier_token)
    )
    assert resp.status_code == 200, resp.text
    return resp.json()


def _create_approved_branch(client, supplier_token, admin_token, merchant_id):
    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),
    )
    return branch


def _create_category(client, supplier_token, branch_id, name="Produce"):
    return client.post(
        f"/api/v1/branches/{branch_id}/categories",
        json={"name": name},
        headers=_auth_headers(supplier_token),
    ).json()


def _create_item(client, supplier_token, branch_id, category_id, **overrides):
    payload = {"name": "Item", "price": "10.00"}
    payload.update(overrides)
    return client.post(
        f"/api/v1/branches/{branch_id}/categories/{category_id}/items",
        json=payload,
        headers=_auth_headers(supplier_token),
    )


@pytest.fixture()
def grocery_setup(client, supplier_token, admin_token):
    """A grocery merchant with one approved branch and one category —
    tests add items with whatever unit_of_measure they need."""
    merchant = _create_merchant(client, supplier_token, business_type="grocery")
    branch = _create_approved_branch(
        client, supplier_token, admin_token, merchant["id"]
    )
    category = _create_category(client, supplier_token, branch["id"])
    return merchant, branch, category


# --- business_type ------------------------------------------------------


def test_merchant_business_type_defaults_to_restaurant(client, supplier_token):
    merchant = _create_merchant(client, supplier_token, business_type=None)
    assert merchant["business_type"] == "restaurant"


def test_merchant_business_type_can_be_grocery(client, supplier_token):
    merchant = _create_merchant(client, supplier_token, business_type="grocery")
    assert merchant["business_type"] == "grocery"


def test_merchant_rejects_invalid_business_type(client, supplier_token):
    resp = client.post(
        "/api/v1/merchants",
        json={"name": "Bad", "business_type": "pharmacy"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 422


def test_list_merchants_filters_by_business_type(
    client, supplier_token, admin_token, customer_token
):
    restaurant = _create_merchant(client, supplier_token, name="Wow Burger")
    grocery = _create_merchant(client, supplier_token, business_type="grocery")
    for merchant in (restaurant, grocery):
        branch = _create_approved_branch(
            client, supplier_token, admin_token, merchant["id"]
        )
        _create_category(client, supplier_token, branch["id"])

    resp = client.get(
        "/api/v1/merchants",
        params={"business_type": "grocery"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200
    assert [m["id"] for m in resp.json()] == [grocery["id"]]

    resp = client.get(
        "/api/v1/merchants",
        params={"business_type": "restaurant"},
        headers=_auth_headers(customer_token),
    )
    assert [m["id"] for m in resp.json()] == [restaurant["id"]]


# --- GroceryItemDetails: creating an item with a unit of measure --------


def test_item_without_unit_of_measure_has_none_in_response(
    client, supplier_token, grocery_setup
):
    _merchant, branch, category = grocery_setup
    resp = _create_item(client, supplier_token, branch["id"], category["id"])
    assert resp.status_code == 200, resp.text
    assert resp.json()["unit_of_measure"] is None


def test_item_with_unit_of_measure_creates_grocery_details(
    client, supplier_token, db_session, grocery_setup
):
    from app.models.grocery import GroceryItemDetails

    _merchant, branch, category = grocery_setup
    resp = _create_item(
        client,
        supplier_token,
        branch["id"],
        category["id"],
        name="Rice",
        unit_of_measure="kg",
    )
    assert resp.status_code == 200, resp.text
    item = resp.json()
    assert item["unit_of_measure"] == "kg"

    details = (
        db_session.query(GroceryItemDetails)
        .filter(GroceryItemDetails.menu_item_id == uuid.UUID(item["id"]))
        .first()
    )
    assert details is not None
    assert details.unit_of_measure == "kg"


def test_branch_menu_listing_includes_unit_of_measure(
    client, supplier_token, grocery_setup
):
    _merchant, branch, category = grocery_setup
    _create_item(
        client,
        supplier_token,
        branch["id"],
        category["id"],
        name="Rice",
        unit_of_measure="kg",
    )
    _create_item(client, supplier_token, branch["id"], category["id"], name="Soda")

    resp = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(supplier_token)
    )
    assert resp.status_code == 200, resp.text
    items = {i["name"]: i for i in resp.json()["categories"][0]["items"]}
    assert items["Rice"]["unit_of_measure"] == "kg"
    assert items["Soda"]["unit_of_measure"] is None


# --- Fractional cart quantity for grocery items -------------------------


def test_fractional_quantity_allowed_for_item_with_unit_of_measure(
    client, supplier_token, customer_token, grocery_setup
):
    _merchant, branch, category = grocery_setup
    item = _create_item(
        client,
        supplier_token,
        branch["id"],
        category["id"],
        name="Rice",
        unit_of_measure="kg",
    ).json()

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 0.5},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    cart_item = resp.json()["items"][0]
    assert cart_item["quantity"] == "0.500"
    assert cart_item["unit_of_measure"] == "kg"


def test_fractional_quantity_rejected_for_item_without_unit_of_measure(
    client, supplier_token, customer_token, grocery_setup
):
    _merchant, branch, category = grocery_setup
    item = _create_item(client, supplier_token, branch["id"], category["id"]).json()

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 0.5},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 422


def test_update_item_rejects_fractional_quantity_without_unit_of_measure(
    client, supplier_token, customer_token, grocery_setup
):
    _merchant, branch, category = grocery_setup
    item = _create_item(client, supplier_token, branch["id"], category["id"]).json()
    cart = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    ).json()
    cart_item_id = cart["items"][0]["id"]

    resp = client.patch(
        f"/api/v1/cart/items/{cart_item_id}",
        json={"quantity": 1.5},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 422


def test_update_item_allows_fractional_quantity_with_unit_of_measure(
    client, supplier_token, customer_token, grocery_setup
):
    _merchant, branch, category = grocery_setup
    item = _create_item(
        client,
        supplier_token,
        branch["id"],
        category["id"],
        name="Rice",
        unit_of_measure="kg",
    ).json()
    cart = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    ).json()
    cart_item_id = cart["items"][0]["id"]

    resp = client.patch(
        f"/api/v1/cart/items/{cart_item_id}",
        json={"quantity": 1.25},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["items"][0]["quantity"] == "1.250"


def test_whole_number_quantity_still_works_for_restaurant_items(
    client, supplier_token, customer_token, grocery_setup
):
    """Sanity check: whole-number quantities (the common case) aren't
    broken by the fractional-quantity support added for grocery."""
    _merchant, branch, category = grocery_setup
    item = _create_item(client, supplier_token, branch["id"], category["id"]).json()

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 3},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["items"][0]["quantity"] == "3.000"
