# 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.

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

from debusine.artifacts.models import CollectionCategory
from debusine.db.models.collections import (
    _CollectionItemTypes as CollectionItemTypes,
)


def remove_explicit_archive_suite_children(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """
    Remove Suite collections as Archive child items.

    Suites are always part of the archive in their workspace, and suites cannot
    be part of an archive from a different workspace.
    """
    CollectionItem = apps.get_model("db", "CollectionItem")
    CollectionItem.objects.filter(
        child_type=CollectionItemTypes.COLLECTION,
        parent_category=CollectionCategory.ARCHIVE,
        category=CollectionCategory.SUITE,
    ).delete()


class Migration(migrations.Migration):
    dependencies = [
        ("db", "0067_collectionitem_db_ci_suite_dbgsym_id_idx"),
    ]
    operations = [
        migrations.RunPython(
            remove_explicit_archive_suite_children, migrations.RunPython.noop
        ),
    ]
