import structlog
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from vbv_lernwelt.simpletodo.models import SimpleTask, SimpleList

logger = structlog.get_logger(__name__)


class SimpleTaskSerializer(ModelSerializer):
    list_title = serializers.CharField(max_length=100)

    class Meta:
        model = SimpleTask
        fields = [
            "id",
            "title",
            "text",
            "done",
            "deadline",
            "list_title",
        ]

    def create(self, validated_data):
        user = validated_data.pop("user", None)
        if user is None:
            raise serializers.ValidationError("User is required")

        list_title = validated_data.pop("list_title")
        simple_list, _ = SimpleList.objects.get_or_create(title=list_title, user=user)

        validated_data["list"] = simple_list

        logger.debug(
            "Creating task",
            label="simpletodo",
            dt={"s1": 3, "s2": 4},
            title=validated_data.get("title"),
            list_title=list_title,
        )
        return super().create(validated_data)
