import logging
import re

import pytest

from app.core import security
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

SUPERADMIN_PHONE = "0911111111"
ADMIN_PHONE = "0922222222"
COURIER_PHONE = "0933333333"
SUPPLIER_PHONE = "0944444444"
SEED_PIN = "111111"


def _extract_otp_from_logs(caplog: pytest.LogCaptureFixture) -> str:
    for record in reversed(caplog.records):
        match = re.search(r"code is (\d+)\.", record.message)
        if match:
            return match.group(1)
    raise AssertionError("No OTP code found in logs")


def _seed_user(db_session, phone, name, role, pin=SEED_PIN, email=None):
    """Insert a User directly, bypassing the API — this is what
    app.commands.seed_superadmin does for the first superadmin, and
    what a fixture needs to do for any admin/superadmin used to drive
    the endpoints under test (there's no API that creates one).
    Normalizes the phone the same way the API would (a raw local-format
    number stored as-is would never match a normalized login lookup)."""
    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 superadmin_token(client, db_session):
    _seed_user(db_session, SUPERADMIN_PHONE, "Super Admin", UserRole.SUPERADMIN)
    return _login(client, SUPERADMIN_PHONE)


@pytest.fixture()
def admin_token(client, db_session):
    _seed_user(db_session, ADMIN_PHONE, "Regular Admin", UserRole.ADMIN)
    return _login(client, ADMIN_PHONE)


@pytest.fixture()
def customer_token(client):
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": "0955555555", "name": "A Customer"},
    )
    code = resp.json()["debug_otp"]
    resp = client.post(
        "/api/v1/auth/signup/verify-otp",
        json={"identifier": "0955555555", "otp_code": code},
    )
    token = resp.json()["verification_token"]
    resp = client.post(
        "/api/v1/auth/signup/complete",
        json={"verification_token": token, "pin": "483920"},
    )
    return resp.json()["access_token"]


# --- Authorization on the invite endpoints ------------------------------


def test_invite_courier_requires_authentication(client):
    resp = client.post(
        "/api/v1/admin/couriers",
        json={
            "phone": COURIER_PHONE,
            "name": "A Courier",
            "email": "courier@example.com",
        },
    )
    assert resp.status_code == 401  # no Authorization header at all


def test_invite_courier_rejects_customer(client, customer_token):
    resp = client.post(
        "/api/v1/admin/couriers",
        json={
            "phone": COURIER_PHONE,
            "name": "A Courier",
            "email": "courier@example.com",
        },
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 403


def test_invite_courier_allows_admin(client, admin_token):
    resp = client.post(
        "/api/v1/admin/couriers",
        json={
            "phone": COURIER_PHONE,
            "name": "A Courier",
            "email": "courier@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200


def test_invite_courier_allows_superadmin(client, superadmin_token):
    resp = client.post(
        "/api/v1/admin/couriers",
        json={
            "phone": COURIER_PHONE,
            "name": "A Courier",
            "email": "courier@example.com",
        },
        headers=_auth_headers(superadmin_token),
    )
    assert resp.status_code == 200


def test_invite_admin_rejects_regular_admin(client, admin_token):
    """A regular admin can invite couriers/suppliers but cannot grant
    admin access to anyone — only a superadmin can."""
    resp = client.post(
        "/api/v1/admin/admins",
        json={
            "phone": "0966666666",
            "name": "Wannabe Admin",
            "email": "wannabe@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 403


def test_invite_admin_allows_superadmin(client, superadmin_token):
    resp = client.post(
        "/api/v1/admin/admins",
        json={
            "phone": "0966666666",
            "name": "New Admin",
            "email": "newadmin@example.com",
        },
        headers=_auth_headers(superadmin_token),
    )
    assert resp.status_code == 200
    assert resp.json()["user"]["role"] == "admin"


# --- Invite creates an unactivated account -------------------------------


def test_invite_creates_account_without_a_pin(client, admin_token, caplog):
    with caplog.at_level(logging.INFO, logger="yeneb.sms"):
        resp = client.post(
            "/api/v1/admin/suppliers",
            json={
                "phone": SUPPLIER_PHONE,
                "name": "A Supplier",
                "email": "supplier@example.com",
            },
            headers=_auth_headers(admin_token),
        )
    assert resp.status_code == 200
    body = resp.json()
    assert body["user"]["role"] == "supplier"
    assert body["user"]["phone"] == "+251944444444"
    assert body["user"]["email"] == "supplier@example.com"
    assert body["debug_otp"]  # dev-mode echo, same as customer signup
    _extract_otp_from_logs(
        caplog
    )  # confirms the "SMS" was also sent — invites are always SMS


def test_invite_rejects_missing_email(client, admin_token):
    resp = client.post(
        "/api/v1/admin/couriers",
        json={"phone": COURIER_PHONE, "name": "A Courier"},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 422


def test_invite_rejects_duplicate_phone(client, admin_token):
    client.post(
        "/api/v1/admin/couriers",
        json={
            "phone": COURIER_PHONE,
            "name": "A Courier",
            "email": "courier@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    resp = client.post(
        "/api/v1/admin/suppliers",
        json={
            "phone": COURIER_PHONE,
            "name": "Same Phone",
            "email": "different@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 409


def test_invite_rejects_duplicate_email(client, admin_token):
    client.post(
        "/api/v1/admin/couriers",
        json={
            "phone": COURIER_PHONE,
            "name": "A Courier",
            "email": "shared@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    resp = client.post(
        "/api/v1/admin/suppliers",
        json={
            "phone": SUPPLIER_PHONE,
            "name": "A Supplier",
            "email": "shared@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 409


def test_login_before_activation_is_rejected_clearly(client, admin_token):
    client.post(
        "/api/v1/admin/couriers",
        json={
            "phone": COURIER_PHONE,
            "name": "A Courier",
            "email": "courier@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    resp = client.post(
        "/api/v1/auth/login", json={"identifier": COURIER_PHONE, "pin": "000000"}
    )
    assert resp.status_code == 403
    assert "Activate your account" in resp.json()["detail"]


# --- Activation flow -----------------------------------------------------


def _invite(client, admin_token, phone, name, role_path, email=None):
    resp = client.post(
        f"/api/v1/admin/{role_path}",
        json={
            "phone": phone,
            "name": name,
            "email": email or f"{name.lower().replace(' ', '.')}@example.com",
        },
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    return resp.json()["debug_otp"]


def test_activation_flow_lets_the_invitee_log_in(client, admin_token):
    code = _invite(client, admin_token, COURIER_PHONE, "A Courier", "couriers")

    resp = client.post(
        "/api/v1/auth/activate/verify-otp",
        json={"phone": COURIER_PHONE, "otp_code": code},
    )
    assert resp.status_code == 200, resp.text
    verification_token = resp.json()["verification_token"]

    resp = client.post(
        "/api/v1/auth/activate/complete",
        json={"verification_token": verification_token, "pin": "246810"},
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["access_token"]
    assert body["refresh_token"]
    assert body["user"]["role"] == "courier"
    assert body["user"]["name"] == "A Courier"

    # And an ordinary login with that PIN now works too.
    resp = client.post(
        "/api/v1/auth/login", json={"identifier": COURIER_PHONE, "pin": "246810"}
    )
    assert resp.status_code == 200


def test_activation_cannot_be_repeated(client, admin_token):
    code = _invite(client, admin_token, SUPPLIER_PHONE, "A Supplier", "suppliers")
    resp = client.post(
        "/api/v1/auth/activate/verify-otp",
        json={"phone": SUPPLIER_PHONE, "otp_code": code},
    )
    verification_token = resp.json()["verification_token"]

    resp = client.post(
        "/api/v1/auth/activate/complete",
        json={"verification_token": verification_token, "pin": "246810"},
    )
    assert resp.status_code == 200

    # Same verification_token again — it was single-use.
    resp = client.post(
        "/api/v1/auth/activate/complete",
        json={"verification_token": verification_token, "pin": "998877"},
    )
    assert resp.status_code == 400


def test_activate_complete_rejects_reactivating_an_active_account(client, db_session):
    """Defense in depth: even with a technically-valid, unconsumed
    verification_token, an already-activated account (pin_hash already
    set) can't be re-activated. Not reachable via the normal invite
    flow (invite blocks duplicate phones), so the token is crafted
    directly here to exercise the check in isolation."""
    from datetime import timedelta

    from app.models.otp import OTPPurpose, OTPVerification
    from app.utils.time import utcnow

    _seed_user(db_session, COURIER_PHONE, "Already Active", UserRole.COURIER)

    token = security.generate_verification_token()
    db_session.add(
        OTPVerification(
            identifier=normalize_ethiopian_phone(COURIER_PHONE),
            purpose=OTPPurpose.ACTIVATE_ACCOUNT.value,
            code_hash=security.hash_otp("000000"),
            consumed_at=utcnow(),
            expires_at=utcnow() + timedelta(minutes=5),
            verification_token_hash=security.hash_verification_token(token),
            verification_token_expires_at=utcnow() + timedelta(minutes=10),
        )
    )
    db_session.commit()

    resp = client.post(
        "/api/v1/auth/activate/complete",
        json={"verification_token": token, "pin": "246810"},
    )
    assert resp.status_code == 409


# --- Listing and deactivating users -----------------------------------


def test_list_users_shows_every_role(client, admin_token, db_session):
    _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)
    _seed_user(db_session, SUPPLIER_PHONE, "A Supplier", UserRole.SUPPLIER)

    resp = client.get("/api/v1/admin/users", headers=_auth_headers(admin_token))
    assert resp.status_code == 200, resp.text
    roles = {u["role"] for u in resp.json()}
    assert {"courier", "supplier", "admin"}.issubset(roles)


def test_list_users_filters_by_role(client, admin_token, db_session):
    _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)
    _seed_user(db_session, SUPPLIER_PHONE, "A Supplier", UserRole.SUPPLIER)

    resp = client.get(
        "/api/v1/admin/users",
        params={"role": "courier"},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    assert [u["role"] for u in resp.json()] == ["courier"]


def test_list_users_filters_by_is_active(client, admin_token, db_session):
    courier = _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)
    courier.is_active = False
    db_session.commit()

    resp = client.get(
        "/api/v1/admin/users",
        params={"is_active": False},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    assert [u["id"] for u in resp.json()] == [str(courier.id)]


def test_list_users_rejects_customer(client, customer_token):
    resp = client.get("/api/v1/admin/users", headers=_auth_headers(customer_token))
    assert resp.status_code == 403


def test_deactivate_user(client, admin_token, db_session):
    courier = _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)

    resp = client.patch(
        f"/api/v1/admin/users/{courier.id}/status",
        json={"is_active": False},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["is_active"] is False

    # Immediately blocked from logging in.
    login = client.post(
        "/api/v1/auth/login",
        json={"identifier": normalize_ethiopian_phone(COURIER_PHONE), "pin": SEED_PIN},
    )
    assert login.status_code == 403


def test_deactivating_blocks_an_already_issued_token(client, admin_token, db_session):
    _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)
    courier_token = _login(client, normalize_ethiopian_phone(COURIER_PHONE))

    courier = (
        db_session.query(User)
        .filter(User.phone == normalize_ethiopian_phone(COURIER_PHONE))
        .first()
    )
    client.patch(
        f"/api/v1/admin/users/{courier.id}/status",
        json={"is_active": False},
        headers=_auth_headers(admin_token),
    )

    resp = client.get("/api/v1/auth/me", headers=_auth_headers(courier_token))
    assert resp.status_code == 401


def test_reactivate_user(client, admin_token, db_session):
    courier = _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)
    courier.is_active = False
    db_session.commit()

    resp = client.patch(
        f"/api/v1/admin/users/{courier.id}/status",
        json={"is_active": True},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["is_active"] is True


def test_update_user_status_404_for_unknown_id(client, admin_token):
    resp = client.patch(
        "/api/v1/admin/users/00000000-0000-0000-0000-000000000000/status",
        json={"is_active": False},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 404


def test_update_user_status_rejects_customer(client, customer_token, db_session):
    courier = _seed_user(db_session, COURIER_PHONE, "A Courier", UserRole.COURIER)
    resp = client.patch(
        f"/api/v1/admin/users/{courier.id}/status",
        json={"is_active": False},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 403


def test_regular_admin_cannot_deactivate_another_admin(client, admin_token, db_session):
    other_admin = _seed_user(db_session, "0966000001", "Other Admin", UserRole.ADMIN)
    resp = client.patch(
        f"/api/v1/admin/users/{other_admin.id}/status",
        json={"is_active": False},
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 403


def test_superadmin_can_deactivate_an_admin(client, superadmin_token, db_session):
    other_admin = _seed_user(db_session, "0966000002", "Other Admin", UserRole.ADMIN)
    resp = client.patch(
        f"/api/v1/admin/users/{other_admin.id}/status",
        json={"is_active": False},
        headers=_auth_headers(superadmin_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["is_active"] is False
