from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy as _


class ConfigurationTaux(models.Model):
    MODE_GLOBAL = "GLOBAL"
    MODE_PAR_CIBLE = "PAR_CIBLE"
    MODE_CHOICES = (
        (MODE_GLOBAL, _("Mode général : un taux unique pour tous les points de vente")),
        (
            MODE_PAR_CIBLE,
            _("Taux par cible : point de vente ou mention"),
        ),
    )

    mode = models.CharField(max_length=20, choices=MODE_CHOICES, default=MODE_GLOBAL)
    taux_global = models.DecimalField(
        max_digits=18,
        decimal_places=2,
        default=2800,
        verbose_name=_("Taux global CDF pour 1 USD"),
    )
    modifie_par = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="+", verbose_name=_("Modifiée par"),
    )
    modifie_le = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = _("Configuration des taux")
        verbose_name_plural = _("Configuration des taux")

    def clean(self):
        super().clean()
        if self.taux_global is None or self.taux_global <= 0:
            raise ValidationError({"taux_global": _("Le taux doit être strictement positif.")})
        if self.pk is None and ConfigurationTaux.objects.exists():
            raise ValidationError(_("Une seule configuration des taux est autorisée."))

    def __str__(self):
        if self.mode == self.MODE_PAR_CIBLE:
            return str(self.get_mode_display())
        return f"{self.get_mode_display()} — {self.taux_global} CDF/USD"


class RegleTaux(models.Model):
    point_de_vente = models.OneToOneField(
        "facturation.PointDeVente", on_delete=models.CASCADE, null=True, blank=True,
        related_name="regle_taux", verbose_name=_("Point de vente"),
    )
    mention = models.OneToOneField(
        "G_Affectation.MentionPointDeVente", on_delete=models.CASCADE, null=True, blank=True,
        related_name="regle_taux", verbose_name=_("Mention"),
    )
    taux = models.DecimalField(
        max_digits=18, decimal_places=2,
        verbose_name=_("Taux CDF pour 1 USD"),
    )
    actif = models.BooleanField(default=True, verbose_name=_("Actif"))
    cree_par = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="+", verbose_name=_("Créée par"),
    )
    modifie_par = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="+", verbose_name=_("Modifiée par"),
    )
    cree_le = models.DateTimeField(auto_now_add=True)
    modifie_le = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ("mention__nom", "point_de_vente__nom", "pk")
        verbose_name = _("Règle de taux")
        verbose_name_plural = _("Règles de taux")
        constraints = [
            models.CheckConstraint(
                condition=(
                    Q(point_de_vente__isnull=False, mention__isnull=True)
                    | Q(point_de_vente__isnull=True, mention__isnull=False)
                ),
                name="g_taux_cible_unique",
            ),
            models.CheckConstraint(condition=Q(taux__gt=0), name="g_taux_taux_positif"),
        ]

    def clean(self):
        super().clean()
        if bool(self.point_de_vente_id) == bool(self.mention_id):
            raise ValidationError(_("Choisissez soit un point de vente, soit une mention."))
        if self.taux is None or self.taux <= 0:
            raise ValidationError({"taux": _("Le taux doit être strictement positif.")})

    @property
    def cible(self):
        return self.point_de_vente or self.mention

    def __str__(self):
        return f"{self.cible} — {self.taux} CDF/USD"


class HistoriqueTaux(models.Model):
    ACTION_CONFIGURATION = "CONFIGURATION"
    ACTION_CREATION = "CREATION"
    ACTION_MODIFICATION = "MODIFICATION"
    ACTION_SUPPRESSION = "SUPPRESSION"
    ACTION_CHOICES = (
        (ACTION_CONFIGURATION, _("Configuration globale")),
        (ACTION_CREATION, _("Création")),
        (ACTION_MODIFICATION, _("Modification")),
        (ACTION_SUPPRESSION, _("Suppression")),
    )

    action = models.CharField(max_length=20, choices=ACTION_CHOICES)
    cible_type = models.CharField(max_length=20, blank=True)
    cible_id = models.PositiveBigIntegerField(null=True, blank=True)
    cible_libelle = models.CharField(max_length=255)
    ancien_taux = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    nouveau_taux = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    ancien_mode = models.CharField(max_length=20, blank=True)
    nouveau_mode = models.CharField(max_length=20, blank=True)
    utilisateur = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="+",
    )
    cree_le = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ("-cree_le", "-pk")
        verbose_name = _("Historique de taux")
        verbose_name_plural = _("Historique des taux")

    def __str__(self):
        return f"{self.cible_libelle} — {self.nouveau_taux or self.ancien_taux}"

    @property
    def cible_libelle_affiche(self):
        if self.cible_type == "GLOBAL":
            return _("Tous les points de vente")
        return self.cible_libelle
