import logging
import re

import pytest

PHONE = "0912345678"
NORMALIZED_PHONE = "+251912345678"
NAME = "Abebe Kebede"
EMAIL = "abebe@example.com"
PIN = "483920"


def _extract_otp_from_logs(
    caplog: pytest.LogCaptureFixture, logger_name="yeneb.sms"
) -> str:
    for record in reversed(caplog.records):
        if record.name != logger_name:
            continue
        match = re.search(r"code is (\d+)\.", record.message)
        if match:
            return match.group(1)
    raise AssertionError(f"No OTP code found in {logger_name} logs")


def _start_signup(client, phone=PHONE, name=NAME) -> str:
    """Phone-only signup, step 1 — returns the debug_otp code."""
    resp = client.post("/api/v1/auth/signup/start", json={"phone": phone, "name": name})
    assert resp.status_code == 200, resp.text
    return resp.json()["debug_otp"]


def _start_signup_email(client, email=EMAIL, name=NAME) -> str:
    """Email-only signup, step 1 — returns the debug_otp code."""
    resp = client.post("/api/v1/auth/signup/start", json={"email": email, "name": name})
    assert resp.status_code == 200, resp.text
    return resp.json()["debug_otp"]


def _verify_signup_otp(client, identifier, code) -> str:
    """Runs step 2 and returns the verification_token."""
    resp = client.post(
        "/api/v1/auth/signup/verify-otp",
        json={"identifier": identifier, "otp_code": code},
    )
    assert resp.status_code == 200, resp.text
    return resp.json()["verification_token"]


def _signup(client, phone=PHONE, name=NAME, pin=PIN):
    """Runs the full 3-step phone-only signup flow."""
    code = _start_signup(client, phone, name)
    verification_token = _verify_signup_otp(client, phone, code)
    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):
    """Runs the full 3-step email-only signup flow."""
    code = _start_signup_email(client, email, name)
    verification_token = _verify_signup_otp(client, email, code)
    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 _login(client, identifier, pin=PIN):
    return client.post(
        "/api/v1/auth/login", json={"identifier": identifier, "pin": pin}
    )


def test_signup_flow_creates_account_and_logs_in(client):
    body = _signup(client)

    assert body["token_type"] == "bearer"
    assert body["access_token"]
    assert body["refresh_token"]
    assert body["user"]["phone"] == NORMALIZED_PHONE
    assert body["user"]["name"] == NAME
    assert body["user"]["role"] == "customer"
    assert body["user"]["email"] is None
    assert body["user"]["is_phone_verified"] is True
    assert body["user"]["is_email_verified"] is False
    assert body["user"]["marketing_emails_opt_in"] is False


def test_signup_email_only_creates_account_and_logs_in(client):
    body = _signup_email(client)

    assert body["user"]["email"] == EMAIL
    assert body["user"]["phone"] is None
    assert body["user"]["is_email_verified"] is True
    assert body["user"]["is_phone_verified"] is False

    resp = _login(client, EMAIL)
    assert resp.status_code == 200, resp.text
    assert resp.json()["user"]["email"] == EMAIL


# --- Single-identifier-first: exactly one of phone/email ------------------


def test_signup_rejects_neither_phone_nor_email(client):
    resp = client.post("/api/v1/auth/signup/start", json={"name": NAME})
    assert resp.status_code == 422


def test_signup_rejects_both_phone_and_email(client):
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": PHONE, "name": NAME, "email": EMAIL},
    )
    assert resp.status_code == 422


def test_signup_stores_email_lowercased(client):
    body = _signup_email(client, email="  Abebe.K@Example.com ")
    assert body["user"]["email"] == "abebe.k@example.com"


def test_signup_rejects_malformed_email(client):
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"name": NAME, "email": "not-an-email"},
    )
    assert resp.status_code == 422


def test_signup_start_rejects_duplicate_verified_email(client):
    _signup_email(client, email="taken@example.com")
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"name": "Someone Else", "email": "taken@example.com"},
    )
    assert resp.status_code == 409


def test_signup_start_rejects_duplicate_email_case_insensitively(client):
    _signup_email(client, email="taken@example.com")
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"name": "Someone Else", "email": "TAKEN@EXAMPLE.COM"},
    )
    assert resp.status_code == 409


def test_signup_start_allows_email_that_is_only_unverified_elsewhere(
    client, db_session
):
    """An admin-invited account's email is stored but never gets the
    is_email_verified=True trust upgrade unless the invitee separately
    completes /auth/email/* (activate/* only ever verifies phone) — see
    the User model docstring. That unverified value must not block a
    genuinely different person from later signing up and verifying it
    themselves."""
    from app.models.user import User

    db_session.add(
        User(
            phone="+251900000001",
            name="Invited Courier",
            email="shared@example.com",
            role="courier",
            pin_hash=None,
        )
    )
    db_session.commit()

    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"name": "Someone Else", "email": "shared@example.com"},
    )
    assert resp.status_code == 200, resp.text


@pytest.mark.parametrize(
    "raw", ["0912345678", "+251912345678", "251912345678", "912345678"]
)
def test_signup_accepts_local_and_international_phone_formats(client, raw):
    body = _signup(client, phone=raw)
    assert body["user"]["phone"] == NORMALIZED_PHONE


def test_signup_rejects_invalid_phone(client):
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": "12345", "name": NAME},
    )
    assert resp.status_code == 422


def test_signup_start_rejects_duplicate_verified_phone(client):
    _signup(client)
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": PHONE, "name": NAME},
    )
    assert resp.status_code == 409


def test_signup_verify_otp_rejects_wrong_code(client):
    _start_signup(client)
    resp = client.post(
        "/api/v1/auth/signup/verify-otp",
        json={"identifier": PHONE, "otp_code": "000000"},
    )
    assert resp.status_code == 400
    assert "Incorrect verification code" in resp.json()["detail"]


def test_signup_verify_otp_locks_after_max_attempts(client):
    _start_signup(client)

    for _ in range(5):
        resp = client.post(
            "/api/v1/auth/signup/verify-otp",
            json={"identifier": PHONE, "otp_code": "000000"},
        )
        assert resp.status_code == 400

    resp = client.post(
        "/api/v1/auth/signup/verify-otp",
        json={"identifier": PHONE, "otp_code": "000000"},
    )
    assert "Too many incorrect attempts" in resp.json()["detail"]


def test_signup_complete_rejects_bad_pin_length(client):
    code = _start_signup(client)
    verification_token = _verify_signup_otp(client, PHONE, code)
    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": verification_token, "pin": "123"},
    )
    assert resp.status_code == 422


def test_signup_complete_rejects_unknown_verification_token(client):
    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": "not-a-real-token", "pin": PIN},
    )
    assert resp.status_code == 400


def test_signup_verification_token_is_single_use(client):
    code = _start_signup(client)
    verification_token = _verify_signup_otp(client, PHONE, code)

    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": verification_token, "pin": PIN},
    )
    assert resp.status_code == 200

    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": verification_token, "pin": "998877"},
    )
    assert resp.status_code == 400
    assert "Verify your phone number again" in resp.json()["detail"]


def test_new_otp_request_invalidates_previous_code(client):
    first = _start_signup(client)
    second = _start_signup(client)

    if first == second:
        pytest.skip(
            "Random OTP collision between the two requests; can't test invalidation here."
        )

    resp = client.post(
        "/api/v1/auth/signup/verify-otp",
        json={"identifier": PHONE, "otp_code": first},
    )
    # The first code was replaced (not just consumed), so it's
    # rejected as incorrect rather than "already used" — either way,
    # it no longer works.
    assert resp.status_code == 400
    assert "Incorrect verification code" in resp.json()["detail"]

    resp = client.post(
        "/api/v1/auth/signup/verify-otp",
        json={"identifier": PHONE, "otp_code": second},
    )
    assert resp.status_code == 200


def test_signup_sends_via_sms_for_phone_and_email_for_email(client, caplog):
    with caplog.at_level(logging.INFO):
        _start_signup(client, phone=PHONE)
    assert any(r.name == "yeneb.sms" for r in caplog.records)

    caplog.clear()
    with caplog.at_level(logging.INFO):
        _start_signup_email(client, email=EMAIL)
    assert any(r.name == "yeneb.email" for r in caplog.records)


def test_signup_complete_with_email_sends_a_welcome_email(client, caplog):
    code = _start_signup_email(client, email=EMAIL)
    verification_token = _verify_signup_otp(client, EMAIL, code)

    caplog.clear()
    with caplog.at_level(logging.INFO):
        resp = client.post(
            "/api/v1/auth/signup/complete",
            json={"verification_token": verification_token, "pin": PIN},
        )
    assert resp.status_code == 200, resp.text

    welcome_logs = [
        r
        for r in caplog.records
        if r.name == "yeneb.email" and "Welcome to YENEB CODS" in r.message
    ]
    assert len(welcome_logs) == 1


def test_signup_complete_with_phone_only_sends_no_welcome_email(client, caplog):
    # A phone-only signup never collects an email — there's nowhere to
    # send a welcome email, so none should be attempted.
    caplog.clear()
    with caplog.at_level(logging.INFO):
        _signup(client)

    assert not any(
        r.name == "yeneb.email" and "Welcome to YENEB CODS" in r.message
        for r in caplog.records
    )


def test_me_requires_valid_token(client):
    resp = client.get("/api/v1/auth/me")
    assert resp.status_code == 401  # no Authorization header at all

    body = _signup(client)
    resp = client.get(
        "/api/v1/auth/me", headers={"Authorization": f"Bearer {body['access_token']}"}
    )
    assert resp.status_code == 200
    assert resp.json()["phone"] == NORMALIZED_PHONE

    resp = client.get("/api/v1/auth/me", headers={"Authorization": "Bearer garbage"})
    assert resp.status_code == 401


def test_login_succeeds_with_correct_pin(client):
    _signup(client)
    resp = _login(client, PHONE)
    assert resp.status_code == 200
    assert resp.json()["refresh_token"]
    assert resp.json()["user"]["phone"] == NORMALIZED_PHONE


def test_login_fails_with_wrong_pin(client):
    _signup(client)
    resp = _login(client, PHONE, pin="999999")
    assert resp.status_code == 401


def test_login_fails_for_unknown_phone(client):
    resp = _login(client, PHONE)
    assert resp.status_code == 401


def test_login_locks_account_after_max_failed_attempts(client):
    _signup(client)

    for _ in range(5):
        resp = _login(client, PHONE, pin="999999")
        assert resp.status_code == 401

    resp = _login(client, PHONE)
    assert resp.status_code == 423


# --- Forgot PIN: identifier-based (phone or email) -------------------------


def test_forgot_pin_flow_resets_pin(client):
    _signup(client)

    resp = client.post("/api/v1/auth/forgot-pin/start", json={"identifier": PHONE})
    assert resp.status_code == 200
    code = resp.json()["debug_otp"]

    resp = client.post(
        "/api/v1/auth/forgot-pin/verify-otp",
        json={"identifier": PHONE, "otp_code": code},
    )
    assert resp.status_code == 200
    verification_token = resp.json()["verification_token"]

    new_pin = "112233"
    resp = client.post(
        "/api/v1/auth/forgot-pin/reset",
        json={"verification_token": verification_token, "pin": new_pin},
    )
    assert resp.status_code == 200

    resp = _login(client, PHONE, pin=PIN)
    assert resp.status_code == 401

    resp = _login(client, PHONE, pin=new_pin)
    assert resp.status_code == 200


def test_forgot_pin_flow_works_by_email_for_an_email_only_account(client):
    """An email-only-signup customer has no phone at all — forgot-pin
    must support resetting via the email identifier too, not just
    phone/SMS (see app.api.v1.endpoints.auth.forgot_pin_start)."""
    _signup_email(client)

    resp = client.post("/api/v1/auth/forgot-pin/start", json={"identifier": EMAIL})
    assert resp.status_code == 200
    code = resp.json()["debug_otp"]

    resp = client.post(
        "/api/v1/auth/forgot-pin/verify-otp",
        json={"identifier": EMAIL, "otp_code": code},
    )
    assert resp.status_code == 200
    verification_token = resp.json()["verification_token"]

    new_pin = "112233"
    resp = client.post(
        "/api/v1/auth/forgot-pin/reset",
        json={"verification_token": verification_token, "pin": new_pin},
    )
    assert resp.status_code == 200

    resp = _login(client, EMAIL, pin=new_pin)
    assert resp.status_code == 200


def test_forgot_pin_start_does_not_reveal_whether_account_is_registered(client):
    resp = client.post("/api/v1/auth/forgot-pin/start", json={"identifier": PHONE})
    assert resp.status_code == 200
    assert "registered" in resp.json()["message"]
    assert resp.json()["debug_otp"] is None  # nothing to echo for an unregistered phone


def test_forgot_pin_verify_otp_rejects_wrong_code(client):
    _signup(client)
    client.post("/api/v1/auth/forgot-pin/start", json={"identifier": PHONE})
    resp = client.post(
        "/api/v1/auth/forgot-pin/verify-otp",
        json={"identifier": PHONE, "otp_code": "000000"},
    )
    assert resp.status_code == 400


def test_forgot_pin_reset_rejects_unknown_verification_token(client):
    resp = client.post(
        "/api/v1/auth/forgot-pin/reset",
        json={"verification_token": "not-a-real-token", "pin": "112233"},
    )
    assert resp.status_code == 400


# --- Marketing consent ------------------------------------------------


def test_marketing_consent_defaults_false_and_can_be_opted_in(client):
    body = _signup(client)
    headers = {"Authorization": f"Bearer {body['access_token']}"}
    assert body["user"]["marketing_emails_opt_in"] is False

    resp = client.patch(
        "/api/v1/auth/me/marketing-consent",
        json={"opt_in": True},
        headers=headers,
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["marketing_emails_opt_in"] is True

    resp = client.get("/api/v1/auth/me", headers=headers)
    assert resp.json()["marketing_emails_opt_in"] is True


def test_marketing_consent_requires_authentication(client):
    resp = client.patch("/api/v1/auth/me/marketing-consent", json={"opt_in": True})
    assert resp.status_code == 401  # no Authorization header at all


# --- Refresh tokens ----------------------------------------------------


def test_refresh_issues_a_new_access_token(client):
    body = _signup(client)
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": body["refresh_token"]}
    )
    assert resp.status_code == 200
    new_body = resp.json()
    assert new_body["access_token"]
    # Not asserting new_body["access_token"] != body["access_token"]: JWT
    # claims only have second-granularity timestamps, so two tokens issued
    # for the same user within the same second are legitimately identical.
    assert new_body["user"]["phone"] == NORMALIZED_PHONE


def test_refresh_rotates_the_refresh_token(client):
    body = _signup(client)
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": body["refresh_token"]}
    )
    new_refresh_token = resp.json()["refresh_token"]
    assert new_refresh_token != body["refresh_token"]

    # The new one works.
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": new_refresh_token}
    )
    assert resp.status_code == 200


def test_reusing_a_rotated_refresh_token_revokes_the_whole_session(client):
    body = _signup(client)
    old_refresh_token = body["refresh_token"]

    # Rotate once — old_refresh_token is now dead, a new one was issued.
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": old_refresh_token}
    )
    new_refresh_token = resp.json()["refresh_token"]

    # Reusing the dead token should be treated as a compromise signal...
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": old_refresh_token}
    )
    assert resp.status_code == 401
    assert "signed out" in resp.json()["detail"]

    # ...and kill the token that replaced it too.
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": new_refresh_token}
    )
    assert resp.status_code == 401


def test_reusing_a_rotated_refresh_token_also_blacklists_live_access_tokens(client):
    """Revoking every refresh token on reuse-detection is only half the
    fix — an access token issued *before* the theft was noticed is
    still technically unexpired. This confirms it stops working too,
    not just future refresh calls."""
    body = _signup(client)
    original_access_token = body["access_token"]
    old_refresh_token = body["refresh_token"]

    resp = client.get(
        "/api/v1/auth/me",
        headers={"Authorization": f"Bearer {original_access_token}"},
    )
    assert resp.status_code == 200

    client.post("/api/v1/auth/refresh", json={"refresh_token": old_refresh_token})
    # Reuse the now-dead token — triggers mass invalidation.
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": old_refresh_token}
    )
    assert resp.status_code == 401

    resp = client.get(
        "/api/v1/auth/me",
        headers={"Authorization": f"Bearer {original_access_token}"},
    )
    assert resp.status_code == 401


def test_refresh_rejects_unknown_token(client):
    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": "not-a-real-token"}
    )
    assert resp.status_code == 401


def test_logout_revokes_the_refresh_token(client):
    body = _signup(client)
    resp = client.post(
        "/api/v1/auth/logout", json={"refresh_token": body["refresh_token"]}
    )
    assert resp.status_code == 200

    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": body["refresh_token"]}
    )
    assert resp.status_code == 401


def test_logout_is_idempotent_for_unknown_tokens(client):
    resp = client.post("/api/v1/auth/logout", json={"refresh_token": "never-existed"})
    assert resp.status_code == 200


def test_logout_blacklists_the_access_token_when_sent(client):
    """The access token isn't in LogoutRequest's body — it's read from
    the Authorization header, same as any authenticated call, so a
    client just sends it the normal way alongside the refresh token in
    the body."""
    body = _signup(client)
    access_token = body["access_token"]
    headers = {"Authorization": f"Bearer {access_token}"}

    resp = client.get("/api/v1/auth/me", headers=headers)
    assert resp.status_code == 200

    resp = client.post(
        "/api/v1/auth/logout",
        json={"refresh_token": body["refresh_token"]},
        headers=headers,
    )
    assert resp.status_code == 200

    resp = client.get("/api/v1/auth/me", headers=headers)
    assert resp.status_code == 401


def test_logout_without_an_access_token_still_revokes_the_refresh_token(client):
    """No Authorization header at all — logout has never required one,
    and shouldn't start now. Nothing to blacklist, but the refresh
    token (the mandatory part) is still revoked."""
    body = _signup(client)
    resp = client.post(
        "/api/v1/auth/logout", json={"refresh_token": body["refresh_token"]}
    )
    assert resp.status_code == 200

    resp = client.post(
        "/api/v1/auth/refresh", json={"refresh_token": body["refresh_token"]}
    )
    assert resp.status_code == 401


def test_logout_with_a_garbage_access_token_does_not_error(client):
    body = _signup(client)
    resp = client.post(
        "/api/v1/auth/logout",
        json={"refresh_token": body["refresh_token"]},
        headers={"Authorization": "Bearer not-a-real-token"},
    )
    assert resp.status_code == 200


def test_logout_does_not_blacklist_other_users_sessions(client):
    a = _signup(client, phone="0912345671")
    b = _signup(client, phone="0912345672")

    client.post(
        "/api/v1/auth/logout",
        json={"refresh_token": a["refresh_token"]},
        headers={"Authorization": f"Bearer {a['access_token']}"},
    )

    resp = client.get(
        "/api/v1/auth/me",
        headers={"Authorization": f"Bearer {b['access_token']}"},
    )
    assert resp.status_code == 200


# --- Change PIN (logged in, distinct from the OTP-gated forgot-pin flow) ---


def test_change_pin_succeeds_with_correct_current_pin(client):
    body = _signup(client)
    headers = {"Authorization": f"Bearer {body['access_token']}"}

    resp = client.patch(
        "/api/v1/auth/me/pin",
        json={"current_pin": PIN, "new_pin": "112233"},
        headers=headers,
    )
    assert resp.status_code == 200, resp.text

    assert _login(client, NORMALIZED_PHONE, pin="112233").status_code == 200
    assert _login(client, NORMALIZED_PHONE, pin=PIN).status_code == 401


def test_change_pin_rejects_wrong_current_pin(client):
    body = _signup(client)
    headers = {"Authorization": f"Bearer {body['access_token']}"}

    resp = client.patch(
        "/api/v1/auth/me/pin",
        json={"current_pin": "000000", "new_pin": "112233"},
        headers=headers,
    )
    assert resp.status_code == 401

    # The old PIN still works — nothing changed.
    assert _login(client, NORMALIZED_PHONE, pin=PIN).status_code == 200


def test_change_pin_rejects_invalid_new_pin_format(client):
    body = _signup(client)
    headers = {"Authorization": f"Bearer {body['access_token']}"}

    resp = client.patch(
        "/api/v1/auth/me/pin",
        json={"current_pin": PIN, "new_pin": "123"},
        headers=headers,
    )
    assert resp.status_code == 422


def test_change_pin_requires_authentication(client):
    resp = client.patch(
        "/api/v1/auth/me/pin", json={"current_pin": PIN, "new_pin": "112233"}
    )
    assert resp.status_code == 401  # no Authorization header at all


# --- PIN blocklist (only applies to *setting* a new PIN) -------------------


def test_signup_complete_rejects_weak_pin(client):
    code = _start_signup(client)
    verification_token = _verify_signup_otp(client, PHONE, code)
    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": verification_token, "pin": "123456"},
    )
    assert resp.status_code == 422


def test_forgot_pin_reset_rejects_weak_pin(client):
    _signup(client)
    code = client.post(
        "/api/v1/auth/forgot-pin/start", json={"identifier": PHONE}
    ).json()["debug_otp"]
    verification_token = client.post(
        "/api/v1/auth/forgot-pin/verify-otp",
        json={"identifier": PHONE, "otp_code": code},
    ).json()["verification_token"]

    resp = client.post(
        "/api/v1/auth/forgot-pin/reset",
        json={"verification_token": verification_token, "pin": "000000"},
    )
    assert resp.status_code == 422


def test_change_pin_rejects_weak_new_pin(client):
    body = _signup(client)
    headers = {"Authorization": f"Bearer {body['access_token']}"}

    resp = client.patch(
        "/api/v1/auth/me/pin",
        json={"current_pin": PIN, "new_pin": "654321"},
        headers=headers,
    )
    assert resp.status_code == 422


def test_login_still_allows_an_existing_weak_pin(client, db_session):
    """The blocklist only stops a *new* weak PIN from being chosen —
    someone who already had one (set before this check existed, or
    seeded directly) can still prove they know it at login."""
    from app.core import security
    from app.models.user import User, UserRole

    user = User(
        phone=NORMALIZED_PHONE,
        name=NAME,
        email=None,
        role=UserRole.CUSTOMER.value,
        pin_hash=security.hash_pin("111111"),
        is_phone_verified=True,
        is_email_verified=False,
    )
    db_session.add(user)
    db_session.commit()

    resp = _login(client, NORMALIZED_PHONE, pin="111111")
    assert resp.status_code == 200, resp.text
