"""
Ecriture du journal fiscal e-MCF sur une connexion autocommit.

La fiscalisation tourne dans la transaction de la vente : si celle-ci est
annulee apres la confirmation DGI, la facture existe a la DGI mais plus dans
FacControl. Le journal, ecrit hors de cette transaction, garde la preuve de
chaque echange pour le rapprochement.
"""

import json
import logging
from decimal import Decimal

from django.conf import settings

from .models import JournalFiscal


logger = logging.getLogger(__name__)

JOURNAL_DB_ALIAS = "mcf_passerelle"


def _alias():
    """Connexion autocommit du journal (repli : connexion principale)."""

    alias = getattr(settings, "JOURNAL_FISCAL_DB_ALIAS", JOURNAL_DB_ALIAS)
    return alias if alias in settings.DATABASES else "default"


def _json_safe(value):
    """Rend un payload serialisable en JSON (Decimal, dates...)."""

    if value is None:
        return None
    try:
        return json.loads(json.dumps(value, default=str))
    except (TypeError, ValueError):
        return {"raw": str(value)}


def _decimal_or_none(value):
    if value is None or value == "":
        return None
    try:
        return Decimal(str(value))
    except Exception:
        return None


def open_entry(*, numero, type_facture, commande_ref, demande, total_ttc_local, total_tva_local, canal="EMCF"):
    """Trace une demande de facture envoyee a l'e-MCF. Ne leve jamais."""

    try:
        return JournalFiscal.objects.using(_alias()).create(
            canal=canal,
            numero=str(numero or "")[:80],
            type_facture=str(type_facture or "")[:2],
            commande_ref=commande_ref,
            demande=_json_safe(demande),
            total_ttc_local=_decimal_or_none(total_ttc_local),
            total_tva_local=_decimal_or_none(total_tva_local),
        )
    except Exception as exc:
        logger.warning("Journal fiscal : ecriture impossible pour %s (%s)", numero, exc)
        return None


def update_entry(entry, **fields):
    """Complete une ligne du journal. Ne leve jamais."""

    if entry is None:
        return
    for key in ("demande", "reponse_demande", "reponse_finalisation"):
        if key in fields:
            fields[key] = _json_safe(fields[key])
    for key in ("total_ttc_dgi", "total_tva_dgi"):
        if key in fields:
            fields[key] = _decimal_or_none(fields[key])
    if "message" in fields:
        fields["message"] = str(fields["message"] or "")[:4000]
    try:
        JournalFiscal.objects.using(_alias()).filter(pk=entry.pk).update(**fields)
        for key, value in fields.items():
            setattr(entry, key, value)
    except Exception as exc:
        logger.warning("Journal fiscal : mise a jour impossible pour %s (%s)", entry.numero, exc)


def link_commande(numero, commande_ref):
    """Rattache les lignes du journal d'un numero a la facture enregistree."""

    if not numero or not commande_ref:
        return
    try:
        JournalFiscal.objects.using(_alias()).filter(numero=numero, commande_ref__isnull=True).update(
            commande_ref=commande_ref
        )
    except Exception as exc:
        logger.warning("Journal fiscal : rattachement impossible pour %s (%s)", numero, exc)
