import uuid
from datetime import datetime, timedelta
from decimal import Decimal

from sqlalchemy import case, func
from sqlalchemy.orm import Session

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.utils.time import utcnow


def _since(days: int) -> datetime:
    return utcnow() - timedelta(days=days)


def get_order_status_breakdown(db: Session, days: int) -> dict[str, int]:
    """Every OrderStatus value present, defaulting missing ones to 0 —
    a dashboard shouldn't have to guess whether a status is genuinely
    zero or just wasn't returned."""
    since = _since(days)
    rows = (
        db.query(Order.status, func.count(Order.id))
        .filter(Order.created_at >= since)
        .group_by(Order.status)
        .all()
    )
    counts = {status.value: 0 for status in OrderStatus}
    for status, count in rows:
        counts[status] = count
    return counts


def get_active_courier_count(db: Session) -> int:
    return (
        db.query(func.count(CourierProfile.id))
        .filter(CourierProfile.is_online.is_(True))
        .scalar()
    )


def get_active_branch_count(db: Session) -> int:
    return (
        db.query(func.count(Branch.id))
        .filter(
            Branch.is_active.is_(True),
            Branch.approval_status == BranchApprovalStatus.APPROVED.value,
            Branch.deleted_at.is_(None),
        )
        .scalar()
    )


def get_top_merchants(
    db: Session, days: int, limit: int = 5
) -> list[tuple[uuid.UUID, str, int, Decimal]]:
    """Ranked by order count in the window, across every status —
    "most orders coming in" is the useful "top" signal for a merchant,
    not just completed ones. total_sales alongside it is
    completed-orders-only, since a cancelled or still-in-progress
    order isn't real sales yet."""
    since = _since(days)
    rows = (
        db.query(
            Merchant.id,
            Merchant.name,
            func.count(Order.id),
            func.coalesce(
                func.sum(
                    case(
                        (Order.status == OrderStatus.COMPLETED.value, Order.total),
                        else_=0,
                    )
                ),
                0,
            ),
        )
        .join(Branch, Branch.merchant_id == Merchant.id)
        .join(Order, Order.branch_id == Branch.id)
        .filter(Order.created_at >= since)
        .group_by(Merchant.id, Merchant.name)
        .order_by(func.count(Order.id).desc())
        .limit(limit)
        .all()
    )
    return [(mid, name, count, Decimal(total)) for mid, name, count, total in rows]


def get_top_branches(
    db: Session, days: int, limit: int = 5
) -> list[tuple[uuid.UUID, str, int, Decimal]]:
    """Same ranking as get_top_merchants, one level down — a merchant
    with several branches can have one standout location and several
    quiet ones, which a merchant-level rollup alone would hide."""
    since = _since(days)
    rows = (
        db.query(
            Branch.id,
            Branch.name,
            func.count(Order.id),
            func.coalesce(
                func.sum(
                    case(
                        (Order.status == OrderStatus.COMPLETED.value, Order.total),
                        else_=0,
                    )
                ),
                0,
            ),
        )
        .join(Order, Order.branch_id == Branch.id)
        .filter(Order.created_at >= since)
        .group_by(Branch.id, Branch.name)
        .order_by(func.count(Order.id).desc())
        .limit(limit)
        .all()
    )
    return [(bid, name, count, Decimal(total)) for bid, name, count, total in rows]


def get_platform_revenue(db: Session, days: int) -> Decimal:
    """Yeneb's own cut, not gross order value — service_fee, the same
    revenue-source reasoning as app.models.delivery.CourierEarning
    (couriers keep 100% of delivery_fee; Yeneb's cut is service_fee
    alone). Only counts orders that have actually been paid — a cash
    order only reaches PaymentStatus.PAID at delivery (see
    app.api.v1.endpoints.courier.mark_delivered), so an order still in
    progress hasn't generated real revenue yet."""
    since = _since(days)
    total = (
        db.query(func.coalesce(func.sum(Order.service_fee), 0))
        .filter(
            Order.created_at >= since,
            Order.payment_status == PaymentStatus.PAID.value,
        )
        .scalar()
    )
    return Decimal(total)
