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"
SUPPLIER2_PHONE = "0959000002"
ADMIN_PHONE = "0959000003"
CUSTOMER_PHONE = "0959000004"
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 supplier2_token(client, db_session):
    _seed_user(db_session, SUPPLIER2_PHONE, "Another Supplier", UserRole.SUPPLIER)
    return _login(client, SUPPLIER2_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, token, name, business_type="restaurant"):
    return client.post(
        "/api/v1/merchants",
        json={"name": name, "business_type": business_type},
        headers=_auth_headers(token),
    ).json()


def _create_branch(client, token, merchant_id, name, **overrides):
    payload = {
        "name": name,
        "address": "Somewhere, Addis Ababa",
        "latitude": 9.005,
        "longitude": 38.763,
        "phone": "0911223344",
    }
    payload.update(overrides)
    return client.post(
        f"/api/v1/merchants/{merchant_id}/branches",
        json=payload,
        headers=_auth_headers(token),
    ).json()


def _approve(client, admin_token, branch_id):
    resp = client.patch(
        f"/api/v1/branches/{branch_id}/approve",
        json={"approval_status": "approved"},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text


def _add_item(client, token, branch_id, name):
    category = client.post(
        f"/api/v1/branches/{branch_id}/categories",
        json={"name": "Menu"},
        headers=_auth_headers(token),
    ).json()
    return client.post(
        f"/api/v1/branches/{branch_id}/categories/{category['id']}/items",
        json={"name": name, "price": "50.00"},
        headers=_auth_headers(token),
    ).json()


def test_lists_only_approved_active_branches(
    client, supplier_token, supplier2_token, admin_token, customer_token
):
    merchant = _create_merchant(client, supplier_token, "Approved Place")
    approved_branch = _create_branch(client, supplier_token, merchant["id"], "Bole")
    _approve(client, admin_token, approved_branch["id"])

    merchant2 = _create_merchant(client, supplier2_token, "Pending Place")
    _create_branch(client, supplier2_token, merchant2["id"], "Pending Branch")

    resp = client.get("/api/v1/branches", headers=_auth_headers(customer_token))
    assert resp.status_code == 200, resp.text
    names = {b["name"] for b in resp.json()}
    assert names == {"Bole"}


def test_hides_inactive_branch(client, supplier_token, admin_token, customer_token):
    merchant = _create_merchant(client, supplier_token, "Toggle Place")
    branch = _create_branch(client, supplier_token, merchant["id"], "Toggle Branch")
    _approve(client, admin_token, branch["id"])

    client.patch(
        f"/api/v1/branches/{branch['id']}",
        json={"is_active": False},
        headers=_auth_headers(supplier_token),
    )

    resp = client.get("/api/v1/branches", headers=_auth_headers(customer_token))
    assert resp.json() == []


def test_filters_by_business_type(
    client, supplier_token, supplier2_token, admin_token, customer_token
):
    restaurant = _create_merchant(client, supplier_token, "Food Place", "restaurant")
    restaurant_branch = _create_branch(
        client, supplier_token, restaurant["id"], "Food Branch"
    )
    _approve(client, admin_token, restaurant_branch["id"])

    grocery = _create_merchant(client, supplier2_token, "Grocery Place", "grocery")
    grocery_branch = _create_branch(
        client, supplier2_token, grocery["id"], "Grocery Branch"
    )
    _approve(client, admin_token, grocery_branch["id"])

    resp = client.get(
        "/api/v1/branches",
        params={"business_type": "grocery"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    names = {b["name"] for b in resp.json()}
    assert names == {"Grocery Branch"}


def test_search_matches_branch_name(
    client, supplier_token, admin_token, customer_token
):
    merchant = _create_merchant(client, supplier_token, "Wow Place")
    branch = _create_branch(client, supplier_token, merchant["id"], "Burger Palace")
    _approve(client, admin_token, branch["id"])

    resp = client.get(
        "/api/v1/branches",
        params={"q": "burger"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert [b["name"] for b in resp.json()] == ["Burger Palace"]


def test_search_matches_menu_item_name(
    client, supplier_token, admin_token, customer_token
):
    merchant = _create_merchant(client, supplier_token, "Wow Place")
    branch = _create_branch(client, supplier_token, merchant["id"], "Neutral Name")
    _approve(client, admin_token, branch["id"])
    _add_item(client, supplier_token, branch["id"], "Spicy Burger")

    resp = client.get(
        "/api/v1/branches",
        params={"q": "burger"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert [b["name"] for b in resp.json()] == ["Neutral Name"]


def test_search_ignores_unavailable_item(
    client, supplier_token, admin_token, customer_token
):
    merchant = _create_merchant(client, supplier_token, "Wow Place")
    branch = _create_branch(client, supplier_token, merchant["id"], "Neutral Name")
    _approve(client, admin_token, branch["id"])
    item = _add_item(client, supplier_token, branch["id"], "Spicy Burger")
    client.patch(
        f"/api/v1/branches/{branch['id']}/items/{item['id']}",
        json={"is_available": False},
        headers=_auth_headers(supplier_token),
    )

    resp = client.get(
        "/api/v1/branches",
        params={"q": "burger"},
        headers=_auth_headers(customer_token),
    )
    assert resp.json() == []


def test_search_with_no_matches_returns_empty(
    client, supplier_token, admin_token, customer_token
):
    merchant = _create_merchant(client, supplier_token, "Wow Place")
    branch = _create_branch(client, supplier_token, merchant["id"], "Some Branch")
    _approve(client, admin_token, branch["id"])

    resp = client.get(
        "/api/v1/branches",
        params={"q": "nonexistentfood"},
        headers=_auth_headers(customer_token),
    )
    assert resp.json() == []


# Distance sorting (lat/lng given) requires the postgis extension —
# SQLite (this test suite's DB) has no equivalent, same reasoning as
# app.api.v1.endpoints.merchants._distance_expr's own docstring.
# Verified with a live smoke test against real Postgres instead.


def test_requires_authentication(client):
    resp = client.get("/api/v1/branches")
    assert resp.status_code == 401  # no Authorization header at all
