# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Move task_configuration_id to configured_task_data."""

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


def move_to_configured_task_data(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """Move task_configuration_id to configured_task_data."""
    WorkRequest = apps.get_model("db", "WorkRequest")

    for wr in WorkRequest.objects.filter(
        dynamic_task_data__has_key="task_configuration_id"
    ):
        value = wr.dynamic_task_data.pop("task_configuration_id")
        if value is not None:
            configured_task_data = wr.configured_task_data or {}
            if configured_task_data.get("task_configuration") is None:
                configured_task_data["task_configuration"] = value
                wr.configured_task_data = configured_task_data
        wr.save()


def move_to_dynamic_task_data(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """Move task_configuration_id back to dynamic_task_data."""
    WorkRequest = apps.get_model("db", "WorkRequest")

    for wr in WorkRequest.objects.filter(
        configured_task_data__has_key="task_configuration"
    ):
        value = wr.configured_task_data.pop("task_configuration")
        if value is not None:
            dynamic_task_data = wr.dynamic_task_data or {}
            dynamic_task_data["task_configuration_id"] = value
            wr.dynamic_task_data = dynamic_task_data
        wr.save()


class Migration(migrations.Migration):

    dependencies = [
        ('db', '0019_workflowtemplate_db_workflowtemplate_update_suites'),
    ]

    operations = [
        migrations.RunPython(
            move_to_configured_task_data, move_to_dynamic_task_data
        ),
    ]
