from flask import Blueprint, render_template, request
from flask_login import login_required, current_user

from app.services.permissions import require
from app.services.activity_logger import log_action
from app.services import customer_service, listing
from config import CUSTOMER_RATINGS

bp = Blueprint("dashboard", __name__, url_prefix="")


def _customer_code_sort_key(customer):
    """همون منطق مرتب‌سازی «بر اساس کد مشتری» در قالب: عدد داخل کد (یا شناسه، اگر کد نداشت)."""
    text = str(customer.customer_code or customer.id).strip()
    digits = "".join(ch for ch in text if ch.isdecimal())
    return (0, int(digits), text) if digits else (1, 0, text)


@bp.route("/")
@login_required
@require("dashboard")
def index():
    search = request.args.get("q", "").strip()
    city = request.args.get("city") or None
    status = request.args.get("status") or None
    rating = request.args.get("rating") or None
    sort = request.args.get("sort", "joined_desc")
    filters = dict(search=search, city=city, status=status, rating=rating)

    # رندر همه‌ی مشتری‌ها پشت هم سایت رو کند می‌کرد؛ پیش‌فرض فقط LIST_PAGE_SIZE تا نمایش داده می‌شه.
    if sort == "customer_code":
        # مرتب‌سازی بر اساس کد در دیتابیس انجام نمی‌شه؛ همه رو می‌گیریم، اینجا مرتب می‌کنیم و بعد می‌بُریم
        customers = customer_service.list_customers(**filters, sort=sort)
        customers.sort(key=_customer_code_sort_key)
        total = len(customers)
        customers = listing.cut(customers)
    else:
        total = customer_service.count_customers(**filters)
        customers = customer_service.list_customers(**filters, sort=sort, limit=listing.page_limit())
    cities = customer_service.distinct_cities()

    if search:
        log_action(current_user, "search", "customer", details={"query": search})

    return render_template(
        "dashboard/index.html",
        customers=customers, total=total, cities=cities,
        statuses=customer_service.STATUS_CHOICES, ratings=CUSTOMER_RATINGS,
        sorts=customer_service.SORT_OPTIONS,
        q=search, selected_city=city, selected_status=status,
        selected_rating=rating, selected_sort=sort,
    )
