from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models


class PeriodicTask(models.Model):
    name = models.CharField(max_length=191, unique=True)
    task = models.CharField(max_length=255)
    intervalSeconds = models.PositiveIntegerField(
        validators=(MinValueValidator(1),)
    )
    args = models.JSONField(default=list, blank=True)
    kwargs = models.JSONField(default=dict, blank=True)
    options = models.JSONField(default=dict, blank=True)
    enabled = models.BooleanField(default=True)
    lastRunAt = models.DateTimeField(null=True, blank=True)
    totalRunCount = models.PositiveBigIntegerField(default=0)
    createdDate = models.DateTimeField(auto_now_add=True)
    updatedDate = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ("name",)

    def __str__(self):
        return self.name

    def clean(self):
        super().clean()
        errors = {}
        if not isinstance(self.args, list):
            errors["args"] = "Task arguments must be a JSON list."
        if not isinstance(self.kwargs, dict):
            errors["kwargs"] = "Task keyword arguments must be a JSON object."
        if not isinstance(self.options, dict):
            errors["options"] = "Task options must be a JSON object."
        if errors:
            raise ValidationError(errors)
