from django.conf import settings
from rest_framework import serializers

from jobs.models import Job, JobEvent


class JobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = (
            "id",
            "type",
            "payload",
            "status",
            "priority",
            "available_at",
            "attempts",
            "max_attempts",
            "idempotency_key",
            "locked_by",
            "locked_until",
            "last_error",
            "result",
            "created_at",
            "updated_at",
            "finished_at",
        )
        read_only_fields = (
            "id",
            "status",
            "attempts",
            "locked_by",
            "locked_until",
            "last_error",
            "result",
            "created_at",
            "updated_at",
            "finished_at",
        )


class JobCreateSerializer(serializers.Serializer):
    type = serializers.CharField(max_length=120)
    payload = serializers.JSONField(required=False, default=dict)
    priority = serializers.IntegerField(required=False, min_value=-32768, max_value=32767, default=50)
    available_at = serializers.DateTimeField(required=False, allow_null=True, default=None)
    max_attempts = serializers.IntegerField(
        required=False,
        min_value=1,
        default=lambda: settings.JOB_WORKER_MAX_ATTEMPTS_DEFAULT,
    )
    idempotency_key = serializers.CharField(
        required=False,
        allow_blank=True,
        allow_null=True,
        max_length=255,
        default=None,
    )

    def validate_idempotency_key(self, value):
        if value is None:
            return None
        value = value.strip()
        return value or None


class JobEventSerializer(serializers.ModelSerializer):
    class Meta:
        model = JobEvent
        fields = ("id", "job", "type", "attempt", "worker_id", "message", "data", "created_at")
        read_only_fields = fields
