"""Utilitaires communs pour appliquer les modifications de prix produit."""

from decimal import Decimal, InvalidOperation

from django.db import transaction

from .models import (
    ConditionnementProduit,
    HistoriquePrixProduit,
    Produit,
    ProduitPointVentePrix,
    StockPointDeVente,
)


PRICE_SCOPE_GLOBAL = HistoriquePrixProduit.PORTEE_GLOBAL
PRICE_SCOPE_PDV = HistoriquePrixProduit.PORTEE_POINT_DE_VENTE
PRICE_SCOPE_CHOICES = (PRICE_SCOPE_GLOBAL, PRICE_SCOPE_PDV)


def _legacy_base_conditionnement(produit):
    """Retourne le conditionnement facteur 1 utilise par le POS actuel."""

    return (
        ConditionnementProduit.objects.filter(
            produit=produit,
            facteur_conversion=Decimal("1"),
            actif=True,
        ).order_by("-par_defaut", "id").first()
        or ConditionnementProduit.objects.filter(produit=produit).order_by("id").first()
    )


def normalize_price_scope(value):
    """Retourne la portee de prix reconnue, avec 'partout' par defaut."""

    value = str(value or "").strip().lower()
    return PRICE_SCOPE_PDV if value == PRICE_SCOPE_PDV else PRICE_SCOPE_GLOBAL


def _normalize_price(value):
    if value in (None, ""):
        return None
    try:
        price = Decimal(str(value)).quantize(Decimal("0.01"))
    except (InvalidOperation, TypeError, ValueError):
        raise ValueError("Le prix de vente est invalide.")
    if price <= 0:
        raise ValueError("Le prix de vente doit etre strictement superieur a 0.")
    return price


def _current_point_de_vente_price(produit, pdv):
    if not pdv:
        return produit.prix_vente

    stock_price = (
        StockPointDeVente.objects.filter(produit=produit, point_de_vente=pdv)
        .exclude(prix_vente__isnull=True)
        .values_list("prix_vente", flat=True)
        .first()
    )
    if stock_price is not None:
        return stock_price

    base_conditionnement = _legacy_base_conditionnement(produit)
    pdv_price = (
        ProduitPointVentePrix.objects.filter(
            produit=produit,
            conditionnement=base_conditionnement,
            point_de_vente=pdv,
            actif=True,
        )
        .values_list("prix_vente", flat=True)
        .first()
    )
    return pdv_price if pdv_price is not None else produit.prix_vente


def resolve_prix_pour_tickets(produits, pdv):
    """
    Resout le prix effectif pour une liste de produits selon la priorite PDV.

    Priorite : StockPointDeVente.prix_vente > ProduitPointVentePrix.prix_vente
    > Produit.prix_vente (catalogue global). Utilise la meme logique que
    _current_point_de_vente_price mais en bulk (2 requetes SQL quelle que soit
    la taille de la liste).

    Retourne une liste de tuples (produit, prix, source) ou source est
    'stock', 'pdv' ou 'catalogue'.
    """
    if not produits:
        return []

    if not pdv:
        return [(p, Decimal(str(p.prix_vente)), "catalogue") for p in produits]

    ids = [p.pk for p in produits]

    stock_index = {
        row["produit_id"]: Decimal(str(row["prix_vente"]))
        for row in StockPointDeVente.objects.filter(
            produit_id__in=ids, point_de_vente=pdv
        ).exclude(prix_vente__isnull=True).values("produit_id", "prix_vente")
    }

    pdv_index = {
        row["produit_id"]: Decimal(str(row["prix_vente"]))
        for row in ProduitPointVentePrix.objects.filter(
            produit_id__in=ids,
            conditionnement__facteur_conversion=Decimal("1"),
            point_de_vente=pdv,
            actif=True,
        ).values("produit_id", "prix_vente")
    }

    result = []
    for produit in produits:
        pid = produit.pk
        if pid in stock_index:
            result.append((produit, stock_index[pid], "stock"))
        elif pid in pdv_index:
            result.append((produit, pdv_index[pid], "pdv"))
        else:
            result.append((produit, Decimal(str(produit.prix_vente)), "catalogue"))
    return result


def appliquer_prix_produit(produit, nouveau_prix, pdv, portee, commentaire, user, *, synchroniser_stock=True):
    """
    Applique un prix produit selon la portee choisie et enregistre l'audit.

    - portee 'partout' : catalogue global + prix PDV + prix stock de tous les PDV.
    - portee 'pdv' : prix du point de vente courant seulement.
    """

    price = _normalize_price(nouveau_prix)
    if price is None:
        return None

    portee = normalize_price_scope(portee)
    if portee == PRICE_SCOPE_PDV and pdv is None:
        raise ValueError("Un point de vente est obligatoire pour modifier le prix localement.")

    user_obj = user if getattr(user, "is_authenticated", False) else None
    comment = str(commentaire or "").strip()

    with transaction.atomic():
        locked_product = Produit.objects.select_for_update().get(pk=produit.pk)
        ancien_prix = (
            locked_product.prix_vente
            if portee == PRICE_SCOPE_GLOBAL
            else _current_point_de_vente_price(locked_product, pdv)
        )

        if portee == PRICE_SCOPE_GLOBAL:
            if locked_product.prix_vente != price:
                locked_product.prix_vente = price
                locked_product.save(update_fields=["prix_vente"])

            base_conditionnement = _legacy_base_conditionnement(locked_product)
            if base_conditionnement and base_conditionnement.prix_vente != price:
                base_conditionnement.prix_vente = price
                base_conditionnement.save(update_fields=["prix_vente", "updated_at"])
            ProduitPointVentePrix.objects.filter(
                produit=locked_product,
                conditionnement=base_conditionnement,
            ).update(prix_vente=price)
            if synchroniser_stock:
                StockPointDeVente.objects.filter(produit=locked_product).update(prix_vente=price)

            if pdv is not None:
                ProduitPointVentePrix.objects.update_or_create(
                    conditionnement=base_conditionnement,
                    point_de_vente=pdv,
                    defaults={"produit": locked_product, "prix_vente": price, "actif": True},
                )
        else:
            base_conditionnement = _legacy_base_conditionnement(locked_product)
            ProduitPointVentePrix.objects.update_or_create(
                conditionnement=base_conditionnement,
                point_de_vente=pdv,
                defaults={"produit": locked_product, "prix_vente": price, "actif": True},
            )
            if synchroniser_stock:
                StockPointDeVente.objects.filter(
                    produit=locked_product,
                    point_de_vente=pdv,
                ).update(prix_vente=price)

        return HistoriquePrixProduit.objects.create(
            produit=locked_product,
            ancien_prix=ancien_prix,
            nouveau_prix=price,
            portee=portee,
            point_de_vente=pdv if portee == PRICE_SCOPE_PDV else None,
            commentaire=comment,
            utilisateur=user_obj,
        )


def enregistrer_changement_prix_standard(conditionnement, ancien_prix, commentaire="", user=None):
    """Propage un changement de prix standard d'un conditionnement et journalise l'historique."""

    nouveau_prix = Decimal(str(conditionnement.prix_vente)).quantize(Decimal("0.01"))
    ancien_prix_dec = Decimal(str(ancien_prix)).quantize(Decimal("0.01"))
    user_obj = user if getattr(user, "is_authenticated", False) else None
    comment = str(commentaire or "").strip()

    with transaction.atomic():
        ProduitPointVentePrix.objects.filter(
            conditionnement=conditionnement,
            prix_vente=ancien_prix_dec,
        ).update(prix_vente=nouveau_prix)

        if conditionnement.facteur_conversion == Decimal("1"):
            StockPointDeVente.objects.filter(
                produit=conditionnement.produit,
                prix_vente=ancien_prix_dec,
            ).update(prix_vente=nouveau_prix)
            if conditionnement.produit.prix_vente != nouveau_prix:
                conditionnement.produit.prix_vente = nouveau_prix
                conditionnement.produit.save(update_fields=["prix_vente"])

        return HistoriquePrixProduit.objects.create(
            produit=conditionnement.produit,
            ancien_prix=ancien_prix_dec,
            nouveau_prix=nouveau_prix,
            portee=PRICE_SCOPE_GLOBAL,
            point_de_vente=None,
            commentaire=comment,
            utilisateur=user_obj,
        )
