import uuid

import pytest

from app.core import security
from app.models.menu import MenuItem
from app.models.menu_option import MenuItemOption
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0964000001"
ADMIN_PHONE = "0964000002"
CUSTOMER_PHONE = "0964000003"
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_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",
            "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 _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 _add_to_cart(client, token, item, quantity=1, option_ids=None):
    payload = {"menu_item_id": item["id"], "quantity": quantity}
    if option_ids is not None:
        payload["option_ids"] = option_ids
    return client.post("/api/v1/cart/items", json=payload, headers=_auth_headers(token))


def _checkout(client, token):
    return client.post(
        "/api/v1/orders/checkout",
        json={"delivery_mode": "takeaway", "payment_method": "cash"},
        headers=_auth_headers(token),
    )


def _reorder(client, token, order_id):
    return client.post(
        f"/api/v1/orders/{order_id}/reorder", headers=_auth_headers(token)
    )


# --- Basic reorder -------------------------------------------------------


def test_reorder_requires_authentication(client, branch_and_item, customer_token):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=2)
    order = _checkout(client, customer_token).json()

    resp = client.post(f"/api/v1/orders/{order['id']}/reorder")
    assert resp.status_code == 401  # no Authorization header at all


def test_reorder_404_for_someone_elses_order(
    client, db_session, branch_and_item, customer_token
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)
    order = _checkout(client, customer_token).json()

    _seed_user(db_session, "0964009999", "Someone Else", UserRole.CUSTOMER)
    other_token = _login(client, "0964009999")

    resp = _reorder(client, other_token, order["id"])
    assert resp.status_code == 404


def test_reorder_adds_items_to_empty_cart(client, branch_and_item, customer_token):
    branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=2)
    order = _checkout(client, customer_token).json()

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["added_count"] == 1
    assert body["skipped"] == []
    assert body["cart"]["branch_id"] == branch["id"]
    assert len(body["cart"]["items"]) == 1
    assert body["cart"]["items"][0]["quantity"] == "2.000"


def test_reorder_merges_into_existing_cart_of_same_branch(
    client, branch_and_item, customer_token
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)
    order = _checkout(client, customer_token).json()

    # Cart is empty again after checkout — add the same item manually
    # first, so reorder has to merge into it rather than starting fresh.
    _add_to_cart(client, customer_token, item, quantity=1)

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert len(body["cart"]["items"]) == 1
    assert body["cart"]["items"][0]["quantity"] == "2.000"  # 1 manual + 1 reordered


def test_reorder_works_on_a_cancelled_order(client, branch_and_item, customer_token):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)
    order = _checkout(client, customer_token).json()
    client.post(
        f"/api/v1/orders/{order['id']}/cancel", headers=_auth_headers(customer_token)
    )

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 200, resp.text
    assert resp.json()["added_count"] == 1


def test_reorder_rejects_when_cart_has_a_different_branch(
    client, supplier_token, admin_token, branch_and_item, customer_token
):
    _branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)
    order = _checkout(client, customer_token).json()

    # Build a second, unrelated branch and put something from it in the cart.
    merchant2 = client.post(
        "/api/v1/merchants",
        json={"name": "Fresh Mart"},
        headers=_auth_headers(supplier_token),
    ).json()
    branch2 = client.post(
        f"/api/v1/merchants/{merchant2['id']}/branches",
        json={
            "name": "Piassa Branch",
            "address": "Piassa, Addis Ababa",
            "latitude": 9.035,
            "longitude": 38.749,
            "phone": "0911998877",
        },
        headers=_auth_headers(supplier_token),
    ).json()
    client.patch(
        f"/api/v1/branches/{branch2['id']}/approve",
        json={"approval_status": "approved"},
        headers=_auth_headers(admin_token),
    )
    category2 = client.post(
        f"/api/v1/branches/{branch2['id']}/categories",
        json={"name": "Produce"},
        headers=_auth_headers(supplier_token),
    ).json()
    item2 = client.post(
        f"/api/v1/branches/{branch2['id']}/categories/{category2['id']}/items",
        json={"name": "Rice", "price": "50.00"},
        headers=_auth_headers(supplier_token),
    ).json()
    _add_to_cart(client, customer_token, item2, quantity=1)

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 409
    assert "different merchant" in resp.json()["detail"].lower()


# --- Item/option availability changed since the original order -----------


def test_reorder_skips_item_marked_unavailable_since(
    client, db_session, branch_and_item, customer_token
):
    branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)
    order = _checkout(client, customer_token).json()

    db_item = (
        db_session.query(MenuItem).filter(MenuItem.id == uuid.UUID(item["id"])).first()
    )
    db_item.is_available = False
    db_session.commit()

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 409  # nothing else in the order to add
    assert "still available" in resp.json()["detail"].lower()


def test_reorder_skips_one_unavailable_item_but_adds_the_rest(
    client, db_session, supplier_token, branch_and_item, customer_token
):
    branch, item = branch_and_item
    category_resp = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(customer_token)
    ).json()
    category_id = category_resp["categories"][0]["id"]
    second_item = client.post(
        f"/api/v1/branches/{branch['id']}/categories/{category_id}/items",
        json={"name": "Fries", "price": "40.00"},
        headers=_auth_headers(supplier_token),
    ).json()

    _add_to_cart(client, customer_token, item, quantity=1)
    _add_to_cart(client, customer_token, second_item, quantity=1)
    order = _checkout(client, customer_token).json()

    db_item = (
        db_session.query(MenuItem).filter(MenuItem.id == uuid.UUID(item["id"])).first()
    )
    db_item.is_available = False
    db_session.commit()

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["added_count"] == 1
    assert len(body["skipped"]) == 1
    assert body["skipped"][0]["name"] == "Beef Burger"
    assert len(body["cart"]["items"]) == 1
    assert body["cart"]["items"][0]["name"] == "Fries"


def test_reorder_preserves_options_when_still_available(
    client, supplier_token, branch_and_item, customer_token
):
    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"]])
    order = _checkout(client, customer_token).json()

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 200, resp.text
    cart_item = resp.json()["cart"]["items"][0]
    assert len(cart_item["options"]) == 1
    assert cart_item["options"][0]["name"] == "Extra Cheese"
    assert cart_item["line_total"] == "165.00"  # 150 + 15


def test_reorder_drops_option_that_no_longer_exists_but_keeps_the_item(
    client, db_session, supplier_token, branch_and_item, customer_token
):
    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"]])
    order = _checkout(client, customer_token).json()

    db_option = (
        db_session.query(MenuItemOption)
        .filter(MenuItemOption.id == uuid.UUID(option["id"]))
        .first()
    )
    db_option.is_available = False
    db_session.commit()

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["added_count"] == 1
    assert body["skipped"] == []  # the item itself is still fine
    cart_item = body["cart"]["items"][0]
    assert cart_item["options"] == []
    assert cart_item["line_total"] == "150.00"  # option dropped, no +15


def test_reorder_rejects_when_branch_closed(
    client, db_session, branch_and_item, customer_token
):
    from app.models.branch import Branch as BranchModel

    branch, item = branch_and_item
    _add_to_cart(client, customer_token, item, quantity=1)
    order = _checkout(client, customer_token).json()

    db_branch = (
        db_session.query(BranchModel)
        .filter(BranchModel.id == uuid.UUID(branch["id"]))
        .first()
    )
    db_branch.is_active = False
    db_session.commit()

    resp = _reorder(client, customer_token, order["id"])
    assert resp.status_code == 409
    assert "closed" in resp.json()["detail"].lower()
