import uuid

import pytest
from sqlalchemy import text

from app.core import security
from app.models.branch import Branch, BranchApprovalStatus
from app.models.merchant import Merchant
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone


def _sqlite_id(value: str) -> str:
    """SQLAlchemy's Uuid type stores rows in SQLite as a 32-char hex
    string with no dashes (confirmed directly against the raw table) —
    a raw text() UPDATE/SELECT keyed on the dashed string form (e.g.
    straight from an API response's "id" field) silently matches zero
    rows. Bypassing the ORM here is deliberate (these tests mutate a
    row directly to prove the API didn't just re-read it), so the id
    has to be converted to the same form the column actually holds."""
    return uuid.UUID(value).hex


SUPPLIER_PHONE = "0957000001"
ADMIN_PHONE = "0957000002"
CUSTOMER_PHONE = "0957000003"
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)


@pytest.fixture()
def merchant(client, supplier_token):
    resp = client.post(
        "/api/v1/merchants",
        json={"name": "Wow Burger"},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    return resp.json()


@pytest.fixture()
def branch(client, supplier_token, merchant):
    resp = 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),
    )
    assert resp.status_code == 200, resp.text
    return resp.json()


def _approve(client, admin_token, branch_id, status="approved"):
    resp = client.patch(
        f"/api/v1/branches/{branch_id}/approve",
        json={"approval_status": status},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    return resp.json()


def test_get_merchant_serves_cached_data_within_ttl(
    client, db_session, merchant, customer_token
):
    first = client.get(
        f"/api/v1/merchants/{merchant['id']}", headers=_auth_headers(customer_token)
    )
    assert first.json()["name"] == "Wow Burger"

    # Change the row directly, bypassing the API (and any invalidation
    # a write endpoint would trigger) — proves the second read comes
    # from cache, not a fresh query.
    db_session.execute(
        text("UPDATE merchants SET name = 'Renamed' WHERE id = :id"),
        {"id": _sqlite_id(merchant["id"])},
    )
    db_session.commit()

    second = client.get(
        f"/api/v1/merchants/{merchant['id']}", headers=_auth_headers(customer_token)
    )
    assert second.json()["name"] == "Wow Burger"


def test_list_merchants_customer_view_is_cached(
    client, db_session, supplier, admin_token, customer_token, merchant, branch
):
    _approve(client, admin_token, branch["id"])

    first = client.get("/api/v1/merchants", headers=_auth_headers(customer_token))
    assert len(first.json()) == 1

    # A second, fully-approved merchant created directly in the DB —
    # a customer's next list call should still show the cached
    # single-item result, not this new one.
    other = Merchant(owner_id=supplier.id, name="Sneaky Merchant")
    db_session.add(other)
    db_session.commit()
    db_session.add(
        Branch(
            merchant_id=other.id,
            name="Sneaky Branch",
            address="Somewhere",
            latitude=9.0,
            longitude=38.7,
            phone="+251911000000",
            approval_status=BranchApprovalStatus.APPROVED.value,
            is_active=True,
        )
    )
    db_session.commit()

    second = client.get("/api/v1/merchants", headers=_auth_headers(customer_token))
    assert len(second.json()) == 1


def test_approve_branch_invalidates_branch_cache_for_admin_view(
    client, admin_token, branch
):
    _approve(client, admin_token, branch["id"], status="approved")
    first = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(admin_token)
    )
    assert first.json()["approval_status"] == "approved"

    _approve(client, admin_token, branch["id"], status="rejected")
    second = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(admin_token)
    )
    assert second.json()["approval_status"] == "rejected"


def test_create_menu_item_invalidates_branch_cache(
    client, supplier_token, admin_token, branch
):
    _approve(client, admin_token, branch["id"])
    client.get(f"/api/v1/branches/{branch['id']}", headers=_auth_headers(admin_token))

    category = client.post(
        f"/api/v1/branches/{branch['id']}/categories",
        json={"name": "Drinks"},
        headers=_auth_headers(supplier_token),
    ).json()
    client.post(
        f"/api/v1/branches/{branch['id']}/categories/{category['id']}/items",
        json={"name": "Macchiato", "price": "45.00"},
        headers=_auth_headers(supplier_token),
    )

    resp = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(admin_token)
    )
    assert len(resp.json()["categories"]) == 1
    assert len(resp.json()["categories"][0]["items"]) == 1


def test_marketplace_browse_serves_cached_data_within_ttl(
    client, db_session, admin_token, customer_token, branch
):
    _approve(client, admin_token, branch["id"])
    first = client.get("/api/v1/branches", headers=_auth_headers(customer_token))
    assert first.json()[0]["name"] == "Bole Branch"

    db_session.execute(
        text("UPDATE branches SET name = 'Renamed' WHERE id = :id"),
        {"id": _sqlite_id(branch["id"])},
    )
    db_session.commit()

    second = client.get("/api/v1/branches", headers=_auth_headers(customer_token))
    assert second.json()[0]["name"] == "Bole Branch"  # still the cached value


def test_marketplace_browse_with_a_search_term_is_never_cached(
    client, db_session, admin_token, customer_token, branch
):
    _approve(client, admin_token, branch["id"])
    client.get(
        "/api/v1/branches", params={"q": "Bole"}, headers=_auth_headers(customer_token)
    )

    db_session.execute(
        text("UPDATE branches SET name = 'Renamed' WHERE id = :id"),
        {"id": _sqlite_id(branch["id"])},
    )
    db_session.commit()

    second = client.get(
        "/api/v1/branches", params={"q": "Bole"}, headers=_auth_headers(customer_token)
    )
    # No cached-stale hit — either reflects the rename live, or (since
    # "Bole" no longer matches "Renamed") simply stops appearing.
    names = [b["name"] for b in second.json()]
    assert "Bole Branch" not in names


# A lat/lng-sorted browse would also need to be proven never-cached, same
# as the q-search case above, but it can't be exercised here: sorting by
# distance runs through app.api.v1.endpoints.merchants._distance_expr,
# which compiles to PostGIS-only SQL (ST_Distance/geography casts) that
# SQLite can't execute at all — the same pre-existing limitation already
# documented on app.services.dispatch's nearest-courier selection ("exer-
# cised by the live smoke test rather than the SQLite-backed pytest
# suite"). That the lat/lng branch never calls cache_get/cache_set is
# visible directly in list_all_branches's source, so this isn't tested
# here at all rather than adding a test that can't run against SQLite.


def test_approve_branch_invalidates_the_marketplace_browse_cache(
    client, admin_token, customer_token, branch
):
    _approve(client, admin_token, branch["id"])
    first = client.get("/api/v1/branches", headers=_auth_headers(customer_token))
    assert len(first.json()) == 1

    _approve(client, admin_token, branch["id"], status="rejected")
    second = client.get("/api/v1/branches", headers=_auth_headers(customer_token))
    assert second.json() == []


def test_marketplace_browse_business_type_filter_has_its_own_cache_entry(
    client, admin_token, customer_token, branch
):
    """restaurant and grocery each get their own cache key — a cached
    restaurant-only browse must never leak into (or block) a
    grocery-only one, or the unfiltered one."""
    _approve(client, admin_token, branch["id"])
    restaurant_view = client.get(
        "/api/v1/branches",
        params={"business_type": "restaurant"},
        headers=_auth_headers(customer_token),
    )
    assert len(restaurant_view.json()) == 1

    grocery_view = client.get(
        "/api/v1/branches",
        params={"business_type": "grocery"},
        headers=_auth_headers(customer_token),
    )
    assert grocery_view.json() == []

    unfiltered_view = client.get(
        "/api/v1/branches", headers=_auth_headers(customer_token)
    )
    assert len(unfiltered_view.json()) == 1
