import pytest

from app.core import security
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0963000001"
ADMIN_PHONE = "0963000002"
CUSTOMER_PHONE = "0963000003"
CUSTOMER2_PHONE = "0963000004"
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 customer2_token(client, db_session):
    _seed_user(db_session, CUSTOMER2_PHONE, "Another Customer", UserRole.CUSTOMER)
    return _login(client, CUSTOMER2_PHONE)


@pytest.fixture()
def branch(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),
    )
    return branch


@pytest.fixture()
def merchant_id(branch):
    return branch["merchant_id"]


def test_favorite_branch(client, branch, customer_token):
    resp = client.post(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 204, resp.text

    detail = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(customer_token)
    )
    assert detail.status_code == 200, detail.text
    assert detail.json()["is_favorited"] is True


def test_favoriting_twice_is_idempotent(client, branch, customer_token):
    for _ in range(2):
        resp = client.post(
            f"/api/v1/branches/{branch['id']}/favorite",
            headers=_auth_headers(customer_token),
        )
        assert resp.status_code == 204, resp.text

    favorites = client.get(
        "/api/v1/customer/favorites", headers=_auth_headers(customer_token)
    ).json()
    assert len(favorites) == 1


def test_unfavorite_removes_it(client, branch, customer_token):
    client.post(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )
    resp = client.delete(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 204, resp.text

    detail = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(customer_token)
    )
    assert detail.json()["is_favorited"] is False


def test_unfavorite_never_favorited_is_noop(client, branch, customer_token):
    resp = client.delete(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 204, resp.text


def test_favorite_requires_customer_role(client, branch, supplier_token):
    resp = client.post(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 403


def test_favorite_404s_for_unapproved_branch(
    client, db_session, admin_token, customer_token
):
    supplier2_token = _login(
        client,
        _seed_user(
            db_session, "0963000005", "Another Supplier", UserRole.SUPPLIER
        ).phone,
    )
    merchant = client.post(
        "/api/v1/merchants",
        json={"name": "Pending Place"},
        headers=_auth_headers(supplier2_token),
    ).json()
    pending_branch = client.post(
        f"/api/v1/merchants/{merchant['id']}/branches",
        json={
            "name": "Unapproved Branch",
            "address": "Somewhere",
            "latitude": 9.0,
            "longitude": 38.7,
            "phone": "0911998877",
        },
        headers=_auth_headers(supplier2_token),
    ).json()

    resp = client.post(
        f"/api/v1/branches/{pending_branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 404


def test_list_favorites_returns_only_own_favorites(
    client, branch, customer_token, customer2_token
):
    client.post(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )

    mine = client.get(
        "/api/v1/customer/favorites", headers=_auth_headers(customer_token)
    ).json()
    assert len(mine) == 1
    assert mine[0]["id"] == branch["id"]
    assert mine[0]["is_favorited"] is True

    other = client.get(
        "/api/v1/customer/favorites", headers=_auth_headers(customer2_token)
    ).json()
    assert other == []


def test_list_favorites_requires_customer_role(client, supplier_token):
    resp = client.get(
        "/api/v1/customer/favorites", headers=_auth_headers(supplier_token)
    )
    assert resp.status_code == 403


def test_list_branches_reflects_is_favorited(
    client, branch, merchant_id, customer_token, customer2_token
):
    client.post(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )

    mine = client.get(
        f"/api/v1/merchants/{merchant_id}/branches",
        headers=_auth_headers(customer_token),
    ).json()
    assert mine[0]["is_favorited"] is True

    other = client.get(
        f"/api/v1/merchants/{merchant_id}/branches",
        headers=_auth_headers(customer2_token),
    ).json()
    assert other[0]["is_favorited"] is False


def test_is_favorited_false_for_non_customer_viewer(client, branch, supplier_token):
    detail = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(supplier_token)
    )
    assert detail.status_code == 200, detail.text
    assert detail.json()["is_favorited"] is False


def test_get_branch_cache_hit_still_reflects_fresh_favorite_status(
    client, branch, customer_token
):
    """The menu payload is cached on first read (see
    app.api.v1.endpoints.branches.get_branch), but is_favorited must
    never be trusted from that cache — favoriting after the cache is
    warm still has to show up on the next read."""
    first = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(customer_token)
    )
    assert first.json()["is_favorited"] is False

    client.post(
        f"/api/v1/branches/{branch['id']}/favorite",
        headers=_auth_headers(customer_token),
    )

    second = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(customer_token)
    )
    assert second.json()["is_favorited"] is True
