import pytest

from app.core import security
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0958000001"
ADMIN_PHONE = "0958000002"
CUSTOMER_PHONE = "0958000003"
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 _make_branch_with_menu(client, supplier_token, admin_token, name_suffix=""):
    merchant = client.post(
        "/api/v1/merchants",
        json={"name": f"Wow Burger{name_suffix}"},
        headers=_auth_headers(supplier_token),
    ).json()
    branch = client.post(
        f"/api/v1/merchants/{merchant['id']}/branches",
        json={
            "name": f"Bole Branch{name_suffix}",
            "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


@pytest.fixture()
def branch_and_item(client, supplier_token, admin_token):
    return _make_branch_with_menu(client, supplier_token, admin_token)


def test_get_cart_when_empty(client, customer_token):
    resp = client.get("/api/v1/cart", headers=_auth_headers(customer_token))
    assert resp.status_code == 200
    assert resp.json() == {
        "id": None,
        "branch_id": None,
        "items": [],
        "subtotal": "0.00",
    }


def test_add_item_requires_customer_role(client, supplier_token, branch_and_item):
    _branch, item = branch_and_item
    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 403


def test_add_item_to_cart(client, customer_token, branch_and_item):
    branch, item = branch_and_item
    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 2},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["branch_id"] == branch["id"]
    assert len(body["items"]) == 1
    assert body["items"][0]["quantity"] == "2.000"
    assert body["subtotal"] == "300.00"


def test_add_same_item_twice_increments_quantity(
    client, customer_token, branch_and_item
):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 2},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert len(body["items"]) == 1
    assert body["items"][0]["quantity"] == "3.000"


def test_add_item_rejects_unavailable_item(
    client, supplier_token, admin_token, customer_token, branch_and_item
):
    branch, item = branch_and_item
    category = client.post(
        f"/api/v1/branches/{branch['id']}/categories",
        json={"name": "Sold Out"},
        headers=_auth_headers(supplier_token),
    ).json()
    unavailable = client.post(
        f"/api/v1/branches/{branch['id']}/categories/{category['id']}/items",
        json={"name": "Out of stock", "price": "50.00", "is_available": False},
        headers=_auth_headers(supplier_token),
    ).json()

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": unavailable["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409


def test_add_item_from_different_branch_rejected(
    client, supplier_token, admin_token, customer_token, branch_and_item
):
    _branch1, item1 = branch_and_item
    _branch2, item2 = _make_branch_with_menu(
        client, supplier_token, admin_token, name_suffix=" 2"
    )

    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item1["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item2["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409


def test_update_item_quantity(client, customer_token, branch_and_item):
    _branch, item = branch_and_item
    add_resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    ).json()
    item_id = add_resp["items"][0]["id"]

    resp = client.patch(
        f"/api/v1/cart/items/{item_id}",
        json={"quantity": 5},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["items"][0]["quantity"] == "5.000"


def test_remove_item_clears_branch_lock(client, customer_token, branch_and_item):
    _branch, item = branch_and_item
    add_resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    ).json()
    item_id = add_resp["items"][0]["id"]

    resp = client.delete(
        f"/api/v1/cart/items/{item_id}", headers=_auth_headers(customer_token)
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["items"] == []
    assert body["branch_id"] is None


def test_clear_cart(client, customer_token, branch_and_item):
    _branch, item = branch_and_item
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    resp = client.delete("/api/v1/cart", headers=_auth_headers(customer_token))
    assert resp.status_code == 200
    assert resp.json()["items"] == []


# --- Options / add-ons + special instructions -----------------------------


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 test_add_item_with_option_prices_it_in(
    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"]
    )

    resp = client.post(
        "/api/v1/cart/items",
        json={
            "menu_item_id": item["id"],
            "quantity": 2,
            "option_ids": [option["id"]],
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    line = body["items"][0]
    assert len(line["options"]) == 1
    assert line["options"][0]["name"] == "Extra Cheese"
    # (150.00 + 15.00) * 2
    assert line["line_total"] == "330.00"
    assert body["subtotal"] == "330.00"


def test_add_item_with_special_instructions(client, customer_token, branch_and_item):
    _branch, item = branch_and_item
    resp = client.post(
        "/api/v1/cart/items",
        json={
            "menu_item_id": item["id"],
            "quantity": 1,
            "special_instructions": "no onions please",
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["items"][0]["special_instructions"] == "no onions please"


def test_add_item_rejects_option_from_another_item(
    client, supplier_token, customer_token, branch_and_item
):
    branch, item = branch_and_item
    other_item = client.post(
        f"/api/v1/branches/{branch['id']}/categories/{item['category_id']}/items",
        json={"name": "Fries", "price": "40.00"},
        headers=_auth_headers(supplier_token),
    ).json()
    group = _create_group(client, supplier_token, branch["id"], other_item["id"])
    option = _create_option(
        client, supplier_token, branch["id"], other_item["id"], group["id"]
    )

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1, "option_ids": [option["id"]]},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409


def test_add_item_rejects_unavailable_option(
    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"]
    )
    db_option = (
        db_session.query(MenuItemOption)
        .filter(MenuItemOption.id == uuid.UUID(option["id"]))
        .first()
    )
    db_option.is_available = False
    db_session.commit()

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1, "option_ids": [option["id"]]},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409


def test_add_item_rejects_multiple_selections_on_single_select_group(
    client, supplier_token, customer_token, branch_and_item
):
    branch, item = branch_and_item
    group = _create_group(
        client, supplier_token, branch["id"], item["id"], selection_type="single"
    )
    option1 = _create_option(
        client, supplier_token, branch["id"], item["id"], group["id"], name="Mild"
    )
    option2 = _create_option(
        client, supplier_token, branch["id"], item["id"], group["id"], name="Spicy"
    )

    resp = client.post(
        "/api/v1/cart/items",
        json={
            "menu_item_id": item["id"],
            "quantity": 1,
            "option_ids": [option1["id"], option2["id"]],
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409


def test_add_item_requires_required_group_selection(
    client, supplier_token, customer_token, branch_and_item
):
    branch, item = branch_and_item
    _create_group(client, supplier_token, branch["id"], item["id"], is_required=True)

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 422


def test_add_item_different_options_stay_separate_lines(
    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"]
    )

    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    resp = client.post(
        "/api/v1/cart/items",
        json={
            "menu_item_id": item["id"],
            "quantity": 1,
            "option_ids": [option["id"]],
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert len(body["items"]) == 2


def test_add_item_same_options_merges_quantity(
    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"]
    )

    client.post(
        "/api/v1/cart/items",
        json={
            "menu_item_id": item["id"],
            "quantity": 1,
            "option_ids": [option["id"]],
            "special_instructions": "well done",
        },
        headers=_auth_headers(customer_token),
    )
    resp = client.post(
        "/api/v1/cart/items",
        json={
            "menu_item_id": item["id"],
            "quantity": 2,
            "option_ids": [option["id"]],
            "special_instructions": "well done",
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert len(body["items"]) == 1
    assert body["items"][0]["quantity"] == "3.000"
