import uuid

from app.services import google_oauth as google_oauth_service
from app.services.google_oauth import GoogleAccount, GoogleTokenError

PHONE = "0912345678"
NORMALIZED_PHONE = "+251912345678"
NAME = "Abebe Kebede"
EMAIL = "abebe@example.com"
PIN = "483920"


def _mock_google_account(monkeypatch, sub="google-sub-1", email=EMAIL, name=NAME):
    monkeypatch.setattr(
        google_oauth_service,
        "verify_google_id_token",
        lambda token: GoogleAccount(sub=sub, email=email, name=name),
    )


def _google_signin(client, id_token="fake-id-token"):
    return client.post("/api/v1/auth/google", json={"id_token": id_token})


def _signup(client, phone=PHONE, name=NAME, pin=PIN):
    """Full phone-only signup+OTP+PIN flow, same as tests/test_auth.py.
    Leaves email unset — see CustomerSignupRequest."""
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": phone, "name": name},
    )
    code = resp.json()["debug_otp"]
    resp = client.post(
        "/api/v1/auth/signup/verify-otp", json={"identifier": phone, "otp_code": code}
    )
    verification_token = resp.json()["verification_token"]
    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": verification_token, "pin": pin},
    )
    assert resp.status_code == 200, resp.text
    return resp.json()


def _signup_email(client, email=EMAIL, name=NAME, pin=PIN):
    """Full email-only signup+OTP+PIN flow — leaves phone unset."""
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"email": email, "name": name},
    )
    code = resp.json()["debug_otp"]
    resp = client.post(
        "/api/v1/auth/signup/verify-otp", json={"identifier": email, "otp_code": code}
    )
    verification_token = resp.json()["verification_token"]
    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": verification_token, "pin": pin},
    )
    assert resp.status_code == 200, resp.text
    return resp.json()


def _auth_headers(token: str) -> dict:
    return {"Authorization": f"Bearer {token}"}


# --- Google Sign-In ----------------------------------------------------


def test_google_signin_creates_new_customer_account(client, monkeypatch):
    _mock_google_account(monkeypatch)
    resp = _google_signin(client)
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["user"]["email"] == EMAIL
    assert body["user"]["name"] == NAME
    assert body["user"]["role"] == "customer"
    assert body["user"]["phone"] is None
    assert body["access_token"]
    assert body["refresh_token"]


def test_google_signin_is_idempotent_for_same_account(client, monkeypatch):
    _mock_google_account(monkeypatch, sub="google-sub-1")
    first = _google_signin(client).json()
    second = _google_signin(client).json()
    assert first["user"]["id"] == second["user"]["id"]


def test_google_signin_does_not_auto_link_on_email_match(
    client, db_session, monkeypatch
):
    """Google verifying this email doesn't prove the person signing in
    is the same person who created the existing email+PIN account —
    google_signin() must never silently merge them. See
    test_google_connect_links_after_pin_confirmation below for the
    deliberate, PIN-confirmed way to actually link."""
    from app.models.user import User

    _signup_email(client)
    _mock_google_account(monkeypatch, sub="google-sub-2", email=EMAIL)

    resp = _google_signin(client)
    assert resp.status_code == 409
    assert "connect Google" in resp.json()["detail"]

    # No new account was silently created, and google_sub stays unclaimed.
    assert db_session.query(User).filter(User.email == EMAIL).count() == 1
    assert (
        db_session.query(User).filter(User.google_sub == "google-sub-2").first() is None
    )


def test_google_signin_rejects_invalid_token(client, monkeypatch):
    def _raise(token):
        raise GoogleTokenError("Invalid Google sign-in token.")

    monkeypatch.setattr(google_oauth_service, "verify_google_id_token", _raise)
    resp = _google_signin(client)
    assert resp.status_code == 401


# --- POST /auth/google/connect (deliberate, PIN-confirmed linking) -------


def test_google_connect_links_after_pin_confirmation(client, monkeypatch):
    signup_body = _signup(client)
    _mock_google_account(monkeypatch, sub="google-sub-connect-1", email=EMAIL)

    resp = client.post(
        "/api/v1/auth/google/connect",
        json={"id_token": "fake-id-token", "pin": PIN},
        headers=_auth_headers(signup_body["access_token"]),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["user"]["id"] == signup_body["user"]["id"]

    # Now google_signin() finds it directly — no more 409.
    resp = _google_signin(client)
    assert resp.status_code == 200, resp.text
    assert resp.json()["user"]["id"] == signup_body["user"]["id"]


def test_google_connect_promotes_email_verification_on_exact_match(
    client, db_session, monkeypatch
):
    """An account can have a stored-but-unverified email — e.g. an
    admin-invited courier/supplier, whose email is reserved at invite
    time but never gets the is_email_verified=True trust upgrade
    unless separately verified via /auth/email/*. Connecting Google
    with a matching, Google-verified email is enough independent proof
    to promote it (see app.api.v1.endpoints.auth.google_connect) —
    single-identifier signup itself can no longer produce this
    stored-but-unverified state, since email is either unset or
    already verified at signup, so this is seeded directly."""
    from app.core import security
    from app.models.user import User

    user = User(
        phone=NORMALIZED_PHONE,
        name=NAME,
        email=EMAIL,
        role="customer",
        pin_hash=security.hash_pin(PIN),
        is_phone_verified=True,
        is_email_verified=False,
    )
    db_session.add(user)
    db_session.commit()

    login_resp = client.post(
        "/api/v1/auth/login", json={"identifier": NORMALIZED_PHONE, "pin": PIN}
    )
    access_token = login_resp.json()["access_token"]
    _mock_google_account(monkeypatch, sub="google-sub-connect-2", email=EMAIL)

    client.post(
        "/api/v1/auth/google/connect",
        json={"id_token": "fake-id-token", "pin": PIN},
        headers=_auth_headers(access_token),
    )
    resp = client.get("/api/v1/auth/me", headers=_auth_headers(access_token))
    assert resp.json()["is_email_verified"] is True


def test_google_connect_rejects_wrong_pin(client, monkeypatch):
    signup_body = _signup(client)
    _mock_google_account(monkeypatch, sub="google-sub-connect-3")

    resp = client.post(
        "/api/v1/auth/google/connect",
        json={"id_token": "fake-id-token", "pin": "000000"},
        headers=_auth_headers(signup_body["access_token"]),
    )
    assert resp.status_code == 401


def test_google_connect_requires_authentication(client, monkeypatch):
    _mock_google_account(monkeypatch)
    resp = client.post(
        "/api/v1/auth/google/connect", json={"id_token": "fake-id-token", "pin": PIN}
    )
    assert resp.status_code == 401  # no Authorization header at all


def test_google_connect_rejects_google_identity_already_linked_elsewhere(
    client, monkeypatch
):
    _mock_google_account(monkeypatch, sub="google-sub-taken", email="first@example.com")
    _google_signin(client)  # creates the first account, claiming this google_sub

    second_signup = _signup(client, phone="0966778899")
    resp = client.post(
        "/api/v1/auth/google/connect",
        json={"id_token": "fake-id-token", "pin": PIN},
        headers=_auth_headers(second_signup["access_token"]),
    )
    assert resp.status_code == 409


def test_google_signin_rejects_disabled_account(client, db_session, monkeypatch):
    from app.models.user import User

    _mock_google_account(monkeypatch, sub="google-sub-3")
    resp = _google_signin(client)
    user_id = resp.json()["user"]["id"]

    db_user = db_session.query(User).filter(User.id == uuid.UUID(user_id)).first()
    db_user.is_active = False
    db_session.commit()

    resp = _google_signin(client)
    assert resp.status_code == 403


def test_google_created_account_can_fetch_me(client, monkeypatch):
    _mock_google_account(monkeypatch)
    body = _google_signin(client).json()

    resp = client.get("/api/v1/auth/me", headers=_auth_headers(body["access_token"]))
    assert resp.status_code == 200
    assert resp.json()["phone"] is None
    assert resp.json()["email"] == EMAIL


# --- Adding a phone to an existing (possibly phone-less) account ---------


def _google_customer_token(client, monkeypatch, sub="google-sub-4"):
    _mock_google_account(monkeypatch, sub=sub)
    return _google_signin(client).json()["access_token"]


def test_add_phone_full_flow(client, monkeypatch):
    token = _google_customer_token(client, monkeypatch)

    resp = client.post(
        "/api/v1/auth/phone/start",
        json={"phone": PHONE},
        headers=_auth_headers(token),
    )
    assert resp.status_code == 200, resp.text
    code = resp.json()["debug_otp"]

    resp = client.post(
        "/api/v1/auth/phone/verify-otp",
        json={"phone": PHONE, "otp_code": code},
        headers=_auth_headers(token),
    )
    assert resp.status_code == 200, resp.text
    verification_token = resp.json()["verification_token"]

    resp = client.post(
        "/api/v1/auth/phone/complete",
        json={"verification_token": verification_token},
        headers=_auth_headers(token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["phone"] == NORMALIZED_PHONE

    me = client.get("/api/v1/auth/me", headers=_auth_headers(token))
    assert me.json()["phone"] == NORMALIZED_PHONE


def test_add_phone_requires_authentication(client):
    resp = client.post("/api/v1/auth/phone/start", json={"phone": PHONE})
    assert resp.status_code == 401  # no Authorization header at all


def test_add_phone_rejects_number_already_used_by_someone_else(client, monkeypatch):
    _signup(client, phone=PHONE)
    token = _google_customer_token(client, monkeypatch)  # a distinct account

    resp = client.post(
        "/api/v1/auth/phone/start",
        json={"phone": PHONE},
        headers=_auth_headers(token),
    )
    assert resp.status_code == 409


def test_add_phone_complete_rejects_unknown_verification_token(client, monkeypatch):
    token = _google_customer_token(client, monkeypatch)
    resp = client.post(
        "/api/v1/auth/phone/complete",
        json={"verification_token": "not-a-real-token"},
        headers=_auth_headers(token),
    )
    assert resp.status_code == 400


# --- Chapa checkout with a phone-less customer ----------------------------


def _seed_staff(db_session, phone, name, role, email):
    from app.core import security
    from app.models.user import User
    from app.utils.phone import normalize_ethiopian_phone

    user = User(
        phone=normalize_ethiopian_phone(phone),
        name=name,
        email=email,
        role=role.value,
        pin_hash=security.hash_pin("111111"),
        is_phone_verified=True,
        is_email_verified=True,
    )
    db_session.add(user)
    db_session.commit()
    db_session.refresh(user)
    return user


def _seed_menu_item(client, db_session):
    """Shared setup for the checkout tests below: a supplier + admin,
    an approved branch, and one orderable item."""
    from app.models.user import UserRole

    supplier = _seed_staff(
        db_session, "0958000099", "A Supplier", UserRole.SUPPLIER, "supplier@x.com"
    )
    admin = _seed_staff(
        db_session, "0958000098", "An Admin", UserRole.ADMIN, "admin@x.com"
    )
    supplier_token = client.post(
        "/api/v1/auth/login", json={"identifier": supplier.phone, "pin": "111111"}
    ).json()["access_token"]
    admin_token = client.post(
        "/api/v1/auth/login", json={"identifier": admin.phone, "pin": "111111"}
    ).json()["access_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 item


def test_chapa_checkout_works_without_a_phone_on_file(client, db_session, monkeypatch):
    """A phone-less (Google-only) customer can still pay via Chapa —
    international cards/PayPal don't need an Ethiopian phone number,
    per Chapa's own docs. This exercises the None-safe phone_number
    handling in app.api.v1.endpoints.orders.checkout."""
    item = _seed_menu_item(client, db_session)

    customer_token = _google_customer_token(client, monkeypatch, sub="google-sub-5")
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    resp = client.post(
        "/api/v1/orders/checkout",
        json={"delivery_mode": "takeaway", "payment_method": "chapa"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text


def test_chapa_checkout_works_without_an_email_on_file(client, db_session):
    """Symmetric to the phone-less case above: email is also optional
    on Chapa's own initialize-payment call (verified against Chapa's
    own docs — only amount, currency, and tx_ref are required), so a
    phone-only-signup customer with no email can pay via Chapa too."""
    item = _seed_menu_item(client, db_session)

    from tests.test_auth import _signup

    customer_token = _signup(client, phone="0977000000")["access_token"]
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    resp = client.post(
        "/api/v1/orders/checkout",
        json={"delivery_mode": "takeaway", "payment_method": "chapa"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
