"""Ajuste global de precios por markup sobre el costo.

Recalcula el precio de venta de los productos a partir de su costo:

    precio = ultimo_costo * (1 + porcentaje/100)

El "ultimo costo" es el costo de la unidad (ProductItem) ingresada mas
reciente con costo cargado (proxy: el id mas alto). Productos sin ninguna
unidad con costo se omiten (no se les puede calcular precio).

Dos endpoints:
  - GET  /admin/pricing/preview  → vista previa (no toca nada)
  - POST /admin/pricing/apply    → sobrescribe Product.price

Ambos aceptan filtros opcionales: category_id, brand_id, active_only.
"""
from decimal import Decimal, InvalidOperation

from flask import jsonify, request
from sqlalchemy import func

from ...extensions import db
from ...models import Product, ProductItem
from ...permissions import require_permission
from . import admin_bp


def _parse_percent(raw):
    try:
        return Decimal(str(raw if raw not in (None, "") else "0"))
    except (InvalidOperation, ValueError):
        return None


def _query_products(params):
    """Filtra productos por categoria / marca / activos. `params` es un dict
    o request.args (ambos exponen .get)."""
    q = Product.query
    cat = params.get("category_id")
    if cat:
        q = q.filter(Product.category_id == int(cat))
    brand = params.get("brand_id")
    if brand:
        q = q.filter(Product.brand_id == int(brand))
    if str(params.get("active_only", "")).lower() == "true":
        q = q.filter(Product.is_active.is_(True))
    return q.order_by(Product.name)


def _last_cost_by_product(product_ids):
    """{product_id: ultimo_costo} usando la unidad con id mas alto que tenga
    costo cargado (id mayor ≈ ingresada mas reciente)."""
    if not product_ids:
        return {}
    sub = (
        db.session.query(
            ProductItem.product_id.label("pid"),
            func.max(ProductItem.id).label("mid"),
        )
        .filter(ProductItem.cost.isnot(None))
        .filter(ProductItem.product_id.in_(product_ids))
        .group_by(ProductItem.product_id)
        .subquery()
    )
    rows = (
        db.session.query(ProductItem.product_id, ProductItem.cost)
        .join(sub, ProductItem.id == sub.c.mid)
        .all()
    )
    return {pid: cost for pid, cost in rows}


@admin_bp.get("/pricing/preview")
@require_permission("pricing.adjust")
def pricing_preview():
    percent = _parse_percent(request.args.get("percent"))
    if percent is None:
        return jsonify(error="porcentaje invalido"), 400
    factor = Decimal("1") + percent / Decimal("100")

    products = _query_products(request.args).all()
    cost_by = _last_cost_by_product([p.id for p in products])

    items = []
    with_cost = 0
    for p in products:
        cost = cost_by.get(p.id)
        new_price = None
        if cost is not None:
            new_price = (Decimal(cost) * factor).quantize(Decimal("0.01"))
            with_cost += 1
        items.append({
            "id": p.id,
            "sku": p.sku,
            "name": p.name,
            "category": p.category.name if p.category else None,
            "brand": p.brand.name if p.brand else None,
            "current_price": str(p.price),
            "last_cost": str(cost) if cost is not None else None,
            "new_price": str(new_price) if new_price is not None else None,
        })

    return jsonify(
        percent=str(percent),
        items=items,
        total=len(items),
        with_cost=with_cost,
        without_cost=len(items) - with_cost,
    )


@admin_bp.post("/pricing/apply")
@require_permission("pricing.adjust")
def pricing_apply():
    data = request.get_json(silent=True) or {}
    percent = _parse_percent(data.get("percent"))
    if percent is None:
        return jsonify(error="porcentaje invalido"), 400
    factor = Decimal("1") + percent / Decimal("100")

    products = _query_products(data).all()
    cost_by = _last_cost_by_product([p.id for p in products])

    updated = 0
    skipped = 0
    for p in products:
        cost = cost_by.get(p.id)
        if cost is None:
            skipped += 1
            continue
        p.price = (Decimal(cost) * factor).quantize(Decimal("0.01"))
        updated += 1

    db.session.commit()
    return jsonify(updated=updated, skipped=skipped)
