# Generated by Django 4.2.13 on 2024-08-23 14:38

from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps

from django_tasks import TaskResultStatus


def separate_results_field(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    DBTaskResult = apps.get_model("django_tasks_database", "DBTaskResult")

    # If a task succeeded, the result is its return value
    DBTaskResult.objects.using(schema_editor.connection.alias).filter(
        status=TaskResultStatus.SUCCEEDED
    ).update(return_value=models.F("result"))

    # If a task failed, the result is the exception data (or nothing)
    DBTaskResult.objects.using(schema_editor.connection.alias).filter(
        status=TaskResultStatus.FAILED
    ).update(exception_data=models.F("result"))


def merge_results_field(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    DBTaskResult = apps.get_model("django_tasks_database", "DBTaskResult")

    # If a task succeeded, the result is its return value
    DBTaskResult.objects.using(schema_editor.connection.alias).filter(
        status=TaskResultStatus.SUCCEEDED
    ).update(result=models.F("return_value"))

    # If a task failed, the result is the exception data (or nothing)
    DBTaskResult.objects.using(schema_editor.connection.alias).filter(
        status=TaskResultStatus.FAILED
    ).update(result=models.F("exception_data"))


class Migration(migrations.Migration):
    dependencies = [
        ("django_tasks_database", "0007_add_separate_results_fields"),
    ]

    operations = [migrations.RunPython(separate_results_field, merge_results_field)]
