"""Soldes dérivés des achats, règlements et avoirs fournisseurs validés.

Un retour est déduit uniquement via son avoir, jamais deux fois. Aucun solde
n'est persisté sur le fournisseur ni aucun paiement fictif généré.
"""

from decimal import Decimal

from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.db.models import Case, Count, F, OuterRef, Q, Subquery, Sum, Value, When
from django.db.models.functions import Coalesce, Greatest, Least
from django.utils import timezone

from achats.models import Achat, AvoirFournisseur
from facturation.access_control import get_accessible_point_de_vente_queryset

from .models import PaiementFournisseur

ZERO = Decimal("0.00")
MONEY_FIELD = models.DecimalField(max_digits=24, decimal_places=2)


def etat_paiement(total_net, total_paye):
    if total_net <= 0:
        return "PAYE"
    if total_paye == 0:
        return "NON_PAYE"
    return "PARTIELLEMENT_PAYE" if total_paye < total_net else "PAYE"


def get_achat_payment_summary(achat):
    summary = get_achat_financial_summary(achat)
    return {key: summary[key] for key in ("total_paye", "solde_a_payer", "etat_paiement")}


def get_achat_financial_summary(achat):
    if not achat.pk:
        paye, avoirs = ZERO, ZERO
    else:
        calculated = achats_avec_soldes(Achat.objects.filter(pk=achat.pk)).get()
        paye, avoirs = calculated.paye_calc, calculated.avoirs_calc
    net = max(achat.total_net - avoirs, ZERO)
    return {"total_paye": paye, "total_avoirs": avoirs, "montant_net_apres_avoirs": net, "solde_a_payer": max(net - paye, ZERO), "credit_fournisseur": max(paye - net, ZERO), "etat_paiement": etat_paiement(net, paye)}


def achats_avec_soldes(queryset=None):
    """Sous-requête corrélée : plusieurs règlements ne multiplient jamais le total achat."""
    queryset = Achat.objects.all() if queryset is None else queryset
    paid = PaiementFournisseur.objects.filter(achat_id=OuterRef("pk"), statut=PaiementFournisseur.STATUT_VALIDE).order_by().values("achat_id").annotate(total=Sum("montant")).values("total")
    credits = AvoirFournisseur.objects.filter(retour__achat_id=OuterRef("pk"), statut="VALIDE", retour__statut="VALIDE").order_by().values("retour__achat_id").annotate(total=Sum("montant_initial")).values("total")
    return queryset.annotate(paye_calc=Coalesce(Subquery(paid, output_field=MONEY_FIELD), Value(ZERO), output_field=MONEY_FIELD), avoirs_calc=Coalesce(Subquery(credits, output_field=MONEY_FIELD), Value(ZERO), output_field=MONEY_FIELD)).annotate(
        net_calc=Greatest(F("total_net") - F("avoirs_calc"), Value(ZERO), output_field=MONEY_FIELD),
    ).annotate(
        solde_calc=Greatest(F("net_calc") - F("paye_calc"), Value(ZERO), output_field=MONEY_FIELD),
        credit_calc=Greatest(F("paye_calc") - F("net_calc"), Value(ZERO), output_field=MONEY_FIELD),
        etat_calc=Case(When(net_calc=0, then=Value("PAYE")), When(paye_calc=0, then=Value("NON_PAYE")), When(paye_calc__lt=F("net_calc"), then=Value("PARTIELLEMENT_PAYE")), default=Value("PAYE"), output_field=models.CharField()),
    )


def avoirs_avec_disponibilites(queryset=None):
    """Affectation dérivée au seul achat source, par ordre PK ; aucun faux paiement.

    Une annulation de paiement recalcule aussi le crédit encore disponible.
    Les applications à d'autres achats nécessiteront leur propre historique.
    """
    queryset = AvoirFournisseur.objects.all() if queryset is None else queryset
    queryset = queryset.filter(statut="VALIDE", retour__statut="VALIDE")
    before = AvoirFournisseur.objects.filter(retour__achat_id=OuterRef("retour__achat_id"), pk__lt=OuterRef("pk"), statut="VALIDE", retour__statut="VALIDE").order_by().values("retour__achat_id").annotate(total=Sum("montant_initial")).values("total")
    paid = PaiementFournisseur.objects.filter(achat_id=OuterRef("retour__achat_id"), statut="VALIDE").order_by().values("achat_id").annotate(total=Sum("montant")).values("total")
    return queryset.annotate(
        avant_calc=Coalesce(Subquery(before, output_field=MONEY_FIELD), Value(ZERO), output_field=MONEY_FIELD),
        paye_source_calc=Coalesce(Subquery(paid, output_field=MONEY_FIELD), Value(ZERO), output_field=MONEY_FIELD),
    ).annotate(utilise_calc=Least(F("montant_initial"), Greatest(F("retour__achat__total_net") - F("paye_source_calc") - F("avant_calc"), Value(ZERO), output_field=MONEY_FIELD), output_field=MONEY_FIELD)).annotate(disponible_calc=F("montant_initial") - F("utilise_calc"))


def achats_accessibles(user):
    return Achat.objects.pour_destinations(get_accessible_point_de_vente_queryset(user))


def paiements_accessibles(user):
    return PaiementFournisseur.objects.filter(achat__in=achats_accessibles(user))


def get_dettes_fournisseurs(user):
    return achats_avec_soldes(achats_accessibles(user).filter(statut=Achat.STATUT_VALIDE)).filter(solde_calc__gt=0)


def get_soldes_fournisseur(fournisseur, user=None):
    """Achats et paiements agrégés séparément, sans mélange USD/CDF, au périmètre PDV."""
    achats = Achat.objects.all() if user is None else achats_accessibles(user)
    achats = achats.filter(fournisseur=fournisseur, statut=Achat.STATUT_VALIDE)
    totals = {row["devise"]: row["total"] for row in achats.order_by().values("devise").annotate(total=Sum("total_net"))}
    paid = {row["devise"]: row["total"] for row in PaiementFournisseur.objects.filter(achat__in=achats, statut=PaiementFournisseur.STATUT_VALIDE).order_by().values("devise").annotate(total=Sum("montant"))}
    counts = {row["devise"]: row for row in achats_avec_soldes(achats).order_by().values("devise").annotate(non_payes=Count("pk", filter=Q(solde_calc__gt=0, paye_calc=0)), partiels=Count("pk", filter=Q(solde_calc__gt=0, paye_calc__gt=0)), dette=Sum("solde_calc"), credit=Sum("credit_calc"), retours=Sum("avoirs_calc"))}
    result = []
    for devise in ("USD", "CDF"):
        row = counts.get(devise, {})
        net = totals.get(devise, ZERO) - row.get("retours", ZERO) - paid.get(devise, ZERO)
        result.append({"devise": devise, "total_achats": totals.get(devise, ZERO), "total_paiements": paid.get(devise, ZERO), "total_retours": row.get("retours", ZERO), "solde": max(net, ZERO), "dette_nette": max(net, ZERO), "avoirs_disponibles": row.get("credit", ZERO), "dettes_achats": row.get("dette", ZERO), "non_payes": row.get("non_payes", 0), "partiels": row.get("partiels", 0)})
    return result


def _verrouiller(paiement):
    if not paiement.pk:
        raise ValidationError("Enregistrez d'abord le brouillon du paiement.")
    # Toujours achat puis paiements (ordre PK), y compris sauvegarde/annulation.
    achat_id = PaiementFournisseur.objects.values_list("achat_id", flat=True).get(pk=paiement.pk)
    achat = Achat.objects.select_for_update().get(pk=achat_id)
    paiements = list(PaiementFournisseur.objects.select_for_update().filter(achat_id=achat_id).order_by("pk"))
    locked = next((item for item in paiements if item.pk == paiement.pk), None)
    if locked is None:
        raise ValidationError("Le paiement n'est plus disponible.")
    locked.achat = achat
    return achat, locked, paiements


@transaction.atomic
def valider_paiement_fournisseur(paiement, user=None):
    achat, locked, paiements = _verrouiller(paiement)
    if not locked.est_modifiable:
        raise ValidationError("Seul un paiement brouillon peut être validé, une seule fois.")
    locked.full_clean()
    paye = sum((item.montant for item in paiements if item.statut == PaiementFournisseur.STATUT_VALIDE), ZERO)
    avoirs = list(AvoirFournisseur.objects.select_for_update().filter(retour__achat=achat, statut="VALIDE", retour__statut="VALIDE").order_by("pk"))
    net = achat.total_net - sum((avoir.montant_initial for avoir in avoirs), ZERO)
    if locked.montant > net - paye:
        raise ValidationError("Le montant dépasse le solde restant de l'achat.")
    now = timezone.now()
    PaiementFournisseur.objects.filter(pk=locked.pk).update(statut=PaiementFournisseur.STATUT_VALIDE, validated_by=user, validated_at=now, updated_at=now)
    paiement.refresh_from_db()
    return paiement


@transaction.atomic
def annuler_paiement_fournisseur(paiement, user=None):
    _, locked, _ = _verrouiller(paiement)
    if locked.statut not in (PaiementFournisseur.STATUT_BROUILLON, PaiementFournisseur.STATUT_VALIDE):
        raise ValidationError("Ce paiement est déjà annulé.")
    now = timezone.now()
    PaiementFournisseur.objects.filter(pk=locked.pk).update(statut=PaiementFournisseur.STATUT_ANNULE, canceled_by=user, canceled_at=now, updated_at=now)
    paiement.refresh_from_db()
    return paiement
