
from management.management.utils.utils import create_audit_log
from management.models.nota_permanente import NotaPermanente
from management.models.utente import Utente
from management.repositories.base import BaseRepository
from management.serializers.nota_permanente_serializer import NotaPermanenteSerializer
from django.db import transaction
from django.contrib.contenttypes.models import ContentType

class NotaPermanenteRepository(BaseRepository):
    entity=NotaPermanente

    @transaction.atomic
    def save(self, dto, user_id=None) -> tuple:
        nota_id = dto.get("id")
        plan_id = dto.get("plan")
        old_values = {}
        instance = None

        if nota_id:
            try:
                instance = NotaPermanente.objects.get(id=nota_id)
            except NotaPermanente.DoesNotExist:
                return False, {"detail": "Nota not found"}
            old_values = NotaPermanenteSerializer(instance).data
            serializer = NotaPermanenteSerializer(instance, data=dto, partial=True)
        else:
            serializer = NotaPermanenteSerializer(data=dto)
        

        serializer.is_valid(raise_exception=True)
        nota = serializer.save()

        
        if instance:
            new_values = {
                "descrizione_nota": 
                    {
                        "old": old_values.get("descrizione_nota"),
                        "new": nota.descrizione_nota
                    },
                "decorrenza": 
                    {
                        "old": old_values.get("decorrenza"),
                        "new": nota.decorrenza.isoformat() if nota.decorrenza else None
                    }
            }
        else:
            new_values = {
                "descrizione_nota": 
                    {
                        "old": '',
                        "new": nota.descrizione_nota
                    },
                "decorrenza": 
                    {
                        "old": '',
                        "new": nota.decorrenza.isoformat() if nota.decorrenza else None
                    }
            }
        activity_type = "MODIFICA NOTA PERMANENTE" if instance else "CREAZIONE NOTA PERMANENTE"

        create_audit_log(
            user=user_id,
            activity_type=activity_type,
            entity=nota,
            entity_name='NotaPermanente',
            entity_id=plan_id,
            old_values=old_values if instance else None,
            new_values=new_values
        )
        return True, {}