# Generated by Django 3.2.18 on 2023-05-30 16:10

from django.db import migrations


def migrate_existing_scheduled_jobs(apps, schema_editor):
    """
    Migrate the existing ScheduledJobs to support the new format.
    1. set sj.kwargs attribute to the old sj.kwargs["data"].
    2. set sj.user to the old sj.kwargs["user"] if the user is not already set.
    3. set sj.queue and sj.celery_kwargs["queue"] to the old sj.kwargs["task_queue"].
    4. change sj.job_class from old "source/module/class_name" to "module.class_name"
    """
    ScheduledJob = apps.get_model("extras", "ScheduledJob")
    for sj in ScheduledJob.objects.all():
        old_kwargs = sj.kwargs
        sj.kwargs = old_kwargs.get("data", {})
        if sj.user is None:
            sj.user = old_kwargs.get("user")
        sj.queue = old_kwargs.get("task_queue", "")
        sj.celery_kwargs["queue"] = old_kwargs.get("task_queue", "")
        sj.job_class = ".".join(sj.job_class.split("/")[-2:])
        sj.task = sj.job_class
        sj.save()


def reverse_migrate_existing_scheduled_jobs(apps, schema_editor):
    """
    Reverse the ScheduledJob Migration / Restore the removed keys in sj.kwargs.
    1. Restore the "data" key from sj.kwargs.
    2. Restore the "commit" key to False.
    3. Restore the "user" key from sj.user.
    4. Restore the "task_queue" from sj.queue.
    5. Restore the "job_class" to a semblance of its old form (will likely be broken)
    """
    ScheduledJob = apps.get_model("extras", "ScheduledJob")
    for sj in ScheduledJob.objects.all():
        sj.kwargs["data"] = sj.kwargs
        sj.kwargs["commit"] = False
        sj.kwargs["user"] = sj.user
        sj.kwargs["task_queue"] = sj.queue or sj.celery_kwargs["queue"]
        sj.job_class = "local/" + "/".join(sj.job_class.rsplit(".", 1))
        sj.save()


class Migration(migrations.Migration):
    dependencies = [
        ("extras", "0090_joblogentry__log_level_data_migration"),
    ]

    operations = [
        migrations.RunPython(
            code=migrate_existing_scheduled_jobs,
            reverse_code=reverse_migrate_existing_scheduled_jobs,
        )
    ]
