"""
Modeles des rapports fiscaux DGI (format e-UF).

Un rapport Z ou A remet a zero les valeurs accumulees : on memorise donc,
pour chaque point de vente, le numero et la periode de chaque cloture afin
que la session suivante reparte de la fin de la precedente. Le contenu calcule
est fige dans `contenu` pour qu'une reimpression reste identique a l'original.
"""

from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.utils.translation import gettext_lazy as _


class RapportFiscalDGI(models.Model):
    """Rapport Z ou A genere, imprimable, couvrant un ou plusieurs points de vente."""

    TYPE_Z = "Z"
    TYPE_A = "A"
    TYPE_CHOICES = (
        (TYPE_Z, _("Rapport Z")),
        (TYPE_A, _("Rapport A")),
    )

    type_rapport = models.CharField(max_length=1, choices=TYPE_CHOICES, db_index=True)
    date_debut = models.DateTimeField(null=True, blank=True)
    date_fin = models.DateTimeField()
    nombre_factures = models.PositiveIntegerField(default=0)
    montant_total = models.DecimalField(max_digits=20, decimal_places=2, default=0)
    contenu = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="rapports_fiscaux_dgi",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ("-created_at", "-pk")
        verbose_name = _("Rapport fiscal DGI")
        verbose_name_plural = _("Rapports fiscaux DGI")

    def __str__(self):
        """Retourne une representation lisible de l'instance."""

        return f"Rapport {self.type_rapport} du {self.date_fin:%d/%m/%Y %H:%M}"


class ClotureFiscaleDGI(models.Model):
    """Compteur Z ou A d'un point de vente, rattache au rapport qui l'a cloture."""

    rapport = models.ForeignKey(RapportFiscalDGI, on_delete=models.CASCADE, related_name="clotures")
    type_rapport = models.CharField(max_length=1, choices=RapportFiscalDGI.TYPE_CHOICES)
    point_de_vente = models.ForeignKey(
        "facturation.PointDeVente",
        on_delete=models.PROTECT,
        related_name="clotures_fiscales_dgi",
    )
    numero = models.PositiveIntegerField()
    # Borne exclusive : vide pour la toute premiere cloture du point de vente.
    date_debut = models.DateTimeField(null=True, blank=True)
    date_fin = models.DateTimeField()

    class Meta:
        ordering = ("rapport", "point_de_vente__nom")
        verbose_name = _("Clôture fiscale DGI")
        verbose_name_plural = _("Clôtures fiscales DGI")
        constraints = [
            models.UniqueConstraint(
                fields=("type_rapport", "point_de_vente", "numero"),
                name="rapports_cloture_dgi_numero_unique",
            ),
        ]
        indexes = [
            models.Index(fields=("type_rapport", "point_de_vente", "date_fin"), name="rapports_cloture_dgi_fin_idx"),
        ]

    def __str__(self):
        """Retourne une representation lisible de l'instance."""

        return f"{self.type_rapport} #{self.numero} - {self.point_de_vente}"
