import itertools
import uuid
from datetime import timedelta
from decimal import Decimal

import pytest

from app.models.branch import Branch, BranchApprovalStatus
from app.models.delivery import CourierProfile
from app.models.merchant import Merchant
from app.models.order import Order, OrderStatus, PaymentStatus
from app.models.user import UserRole
from app.utils.time import utcnow

from .test_admin import (  # noqa: F401 (fixture imports, used by name via injection)
    _auth_headers,
    _seed_user,
    admin_token,
    customer_token,
    superadmin_token,
)

_supplier_phone_counter = itertools.count(1)


def _unique_supplier_phone() -> str:
    return f"09{next(_supplier_phone_counter):08d}"


def _seed_merchant_and_branch(db_session, name="A Merchant", is_active=True):
    supplier = _seed_user(
        db_session, _unique_supplier_phone(), "A Supplier", UserRole.SUPPLIER
    )
    merchant = Merchant(owner_id=supplier.id, name=name)
    db_session.add(merchant)
    db_session.commit()
    branch = Branch(
        merchant_id=merchant.id,
        name=f"{name} Branch",
        address="Somewhere",
        latitude=9.0,
        longitude=38.7,
        phone="+251911000000",
        approval_status=BranchApprovalStatus.APPROVED.value,
        is_active=is_active,
    )
    db_session.add(branch)
    db_session.commit()
    return merchant, branch


def _seed_order(
    db_session,
    customer_id,
    branch_id,
    status=OrderStatus.COMPLETED,
    payment_status=PaymentStatus.PAID,
    total=Decimal("100.00"),
    service_fee=Decimal("5.00"),
    created_at=None,
):
    order = Order(
        customer_id=customer_id,
        branch_id=branch_id,
        status=status.value,
        delivery_mode="takeaway",
        subtotal=Decimal("90.00"),
        delivery_fee=Decimal("0.00"),
        service_fee=service_fee,
        vat=Decimal("5.00"),
        discount_amount=Decimal("0.00"),
        total=total,
        payment_status=payment_status.value,
        tx_ref=f"yeneb-test-{uuid.uuid4()}",
    )
    if created_at is not None:
        order.created_at = created_at
    db_session.add(order)
    db_session.commit()
    return order


@pytest.fixture()
def customer(db_session):
    return _seed_user(db_session, "0977000001", "A Customer", UserRole.CUSTOMER)


def test_analytics_requires_authentication(client):
    resp = client.get("/api/v1/admin/analytics")
    assert resp.status_code == 401


def test_analytics_rejects_customer(client, customer_token):  # noqa: F811
    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(customer_token))
    assert resp.status_code == 403


def test_analytics_order_volume_and_status_breakdown(
    client,
    db_session,
    admin_token,  # noqa: F811
    customer,
):
    _merchant, branch = _seed_merchant_and_branch(db_session)
    _seed_order(db_session, customer.id, branch.id, status=OrderStatus.COMPLETED)
    _seed_order(db_session, customer.id, branch.id, status=OrderStatus.COMPLETED)
    _seed_order(db_session, customer.id, branch.id, status=OrderStatus.CANCELLED)

    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(admin_token))
    assert resp.status_code == 200, resp.text
    body = resp.json()

    assert body["order_volume"] == 3
    breakdown = {row["status"]: row["count"] for row in body["order_status_breakdown"]}
    assert breakdown["completed"] == 2
    assert breakdown["cancelled"] == 1
    assert breakdown["confirmed"] == 0  # every status present, zero-filled


def test_analytics_cancellation_rate(client, db_session, admin_token, customer):  # noqa: F811
    _merchant, branch = _seed_merchant_and_branch(db_session)
    _seed_order(db_session, customer.id, branch.id, status=OrderStatus.COMPLETED)
    _seed_order(db_session, customer.id, branch.id, status=OrderStatus.COMPLETED)
    _seed_order(db_session, customer.id, branch.id, status=OrderStatus.CANCELLED)
    _seed_order(db_session, customer.id, branch.id, status=OrderStatus.CANCELLED)

    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(admin_token))
    assert resp.json()["cancellation_rate"] == 0.5


def test_analytics_cancellation_rate_zero_when_no_orders(client, admin_token):  # noqa: F811
    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(admin_token))
    assert resp.status_code == 200, resp.text
    assert resp.json()["cancellation_rate"] == 0.0
    assert resp.json()["order_volume"] == 0


def test_analytics_excludes_orders_outside_the_window(
    client,
    db_session,
    admin_token,  # noqa: F811
    customer,
):
    _merchant, branch = _seed_merchant_and_branch(db_session)
    _seed_order(db_session, customer.id, branch.id)
    _seed_order(
        db_session,
        customer.id,
        branch.id,
        created_at=utcnow() - timedelta(days=60),
    )

    resp = client.get(
        "/api/v1/admin/analytics?days=30", headers=_auth_headers(admin_token)
    )
    assert resp.json()["order_volume"] == 1


def test_analytics_active_couriers_and_branches(
    client,
    db_session,
    admin_token,  # noqa: F811
    customer,
):
    _merchant, active_branch = _seed_merchant_and_branch(
        db_session, name="Active One", is_active=True
    )
    _seed_merchant_and_branch(db_session, name="Inactive One", is_active=False)

    online_courier = _seed_user(
        db_session, "0988000001", "Online Courier", UserRole.COURIER
    )
    db_session.add(CourierProfile(user_id=online_courier.id, is_online=True))
    offline_courier = _seed_user(
        db_session, "0988000002", "Offline Courier", UserRole.COURIER
    )
    db_session.add(CourierProfile(user_id=offline_courier.id, is_online=False))
    db_session.commit()

    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(admin_token))
    body = resp.json()
    assert body["active_couriers"] == 1
    assert body["active_branches"] == 1


def test_analytics_top_merchants_ranked_by_order_count(
    client,
    db_session,
    admin_token,  # noqa: F811
    customer,
):
    _busy_merchant, busy_branch = _seed_merchant_and_branch(
        db_session, name="Busy Place"
    )
    _quiet_merchant, quiet_branch = _seed_merchant_and_branch(
        db_session, name="Quiet Place"
    )

    for _ in range(3):
        _seed_order(
            db_session,
            customer.id,
            busy_branch.id,
            status=OrderStatus.COMPLETED,
            total=Decimal("50.00"),
        )
    _seed_order(
        db_session,
        customer.id,
        quiet_branch.id,
        status=OrderStatus.COMPLETED,
        total=Decimal("50.00"),
    )

    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(admin_token))
    top = resp.json()["top_merchants"]
    assert top[0]["merchant_name"] == "Busy Place"
    assert top[0]["order_count"] == 3
    assert top[0]["total_sales"] == "150.00"
    assert top[1]["merchant_name"] == "Quiet Place"


def test_analytics_top_branches_ranked_by_order_count(
    client,
    db_session,
    admin_token,  # noqa: F811
    customer,
):
    """One merchant, two branches — proves branches are ranked
    individually, not rolled up under their merchant like
    top_merchants is."""
    merchant, busy_branch = _seed_merchant_and_branch(db_session, name="One Brand")
    quiet_branch = Branch(
        merchant_id=merchant.id,
        name="One Brand — Quiet Branch",
        address="Elsewhere",
        latitude=9.1,
        longitude=38.8,
        phone="+251911000001",
        approval_status=BranchApprovalStatus.APPROVED.value,
        is_active=True,
    )
    db_session.add(quiet_branch)
    db_session.commit()

    for _ in range(2):
        _seed_order(
            db_session,
            customer.id,
            busy_branch.id,
            status=OrderStatus.COMPLETED,
            total=Decimal("40.00"),
        )
    _seed_order(
        db_session,
        customer.id,
        quiet_branch.id,
        status=OrderStatus.COMPLETED,
        total=Decimal("40.00"),
    )

    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(admin_token))
    top = resp.json()["top_branches"]
    assert top[0]["branch_name"] == busy_branch.name
    assert top[0]["order_count"] == 2
    assert top[0]["total_sales"] == "80.00"
    assert top[1]["branch_name"] == "One Brand — Quiet Branch"


def test_analytics_revenue_hidden_from_regular_admin(
    client,
    db_session,
    admin_token,  # noqa: F811
    customer,
):
    _merchant, branch = _seed_merchant_and_branch(db_session)
    _seed_order(
        db_session,
        customer.id,
        branch.id,
        status=OrderStatus.COMPLETED,
        payment_status=PaymentStatus.PAID,
        service_fee=Decimal("5.00"),
    )

    resp = client.get("/api/v1/admin/analytics", headers=_auth_headers(admin_token))
    assert resp.json()["revenue"] is None


def test_analytics_revenue_shown_to_superadmin(
    client,
    db_session,
    superadmin_token,  # noqa: F811
    customer,
):
    _merchant, branch = _seed_merchant_and_branch(db_session)
    _seed_order(
        db_session,
        customer.id,
        branch.id,
        status=OrderStatus.COMPLETED,
        payment_status=PaymentStatus.PAID,
        service_fee=Decimal("5.00"),
    )
    _seed_order(
        db_session,
        customer.id,
        branch.id,
        status=OrderStatus.PENDING_PAYMENT,
        payment_status=PaymentStatus.PENDING,
        service_fee=Decimal("5.00"),
    )

    resp = client.get(
        "/api/v1/admin/analytics", headers=_auth_headers(superadmin_token)
    )
    assert resp.status_code == 200, resp.text
    # Only the PAID order's service_fee counts — the still-pending one
    # hasn't generated real revenue yet.
    assert resp.json()["revenue"] == "5.00"
