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

"""debusine-admin command to delete workspaces."""

from django.core.management import CommandError
from django.db import transaction
from django.db.models import Q

from debusine.db.models import (
    Artifact,
    ArtifactRelation,
    Collection,
    CollectionItem,
    FileInArtifact,
    WorkRequest,
    WorkflowTemplate,
    Workspace,
    default_workspace,
)
from debusine.server.management.debusine_base_command import DebusineBaseCommand


class Command(DebusineBaseCommand):
    """Command to delete a workspace."""

    help = (
        "Delete a workspace. By default it requests confirmation"
        "before deletion"
    )

    def add_arguments(self, parser):
        """Add CLI arguments for the create_workspace command."""
        parser.add_argument(
            '--yes', action='store_true', help='Skips confirmation of deletion'
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='Does not fail if trying to delete nonexistent workspaces',
        )
        parser.add_argument("name", help="Workspace name")

    def handle(self, *, name: str, yes: bool, force: bool, **options):
        """Delete the workspace."""
        try:
            workspace = Workspace.objects.get(name=name)
        except Workspace.DoesNotExist:
            if force:
                return
            else:
                raise CommandError(
                    f"Workspace {name} does not exist",
                    returncode=3,
                )

        # Prevent deletion of default workspace
        if workspace == default_workspace():
            raise CommandError(
                f"Workspace {name} cannot be deleted",
                returncode=3,
            )

        deletion_confirmed = False
        if yes:
            deletion_confirmed = True
        else:
            deletion_answer = input(
                f"Would you like to delete workspace {name}? [yN] "
            )
            deletion_confirmed = deletion_answer.strip() in ('y', 'Y')

        if not deletion_confirmed:
            return

        with transaction.atomic():
            # Since we use on_delete=PROTECT on most models, there may be
            # elements in the model interdependency graphs that we are not
            # deleting yet.
            #
            # It is difficult to test this without having infrastructure to
            # simulate a fully populated database that is kept up to date as
            # new models get added, so for the moment we limit ourselves to
            # adding to this as the need arises.
            WorkflowTemplate.objects.filter(workspace=workspace).delete()
            WorkRequest.objects.filter(workspace=workspace).delete()
            CollectionItem.objects.filter(
                parent_collection__workspace=workspace
            ).delete()
            Collection.objects.filter(workspace=workspace).delete()
            FileInArtifact.objects.filter(
                artifact__workspace=workspace
            ).delete()
            ArtifactRelation.objects.filter(
                Q(artifact__workspace=workspace)
                | Q(target__workspace=workspace)
            ).delete()
            Artifact.objects.filter(workspace=workspace).delete()
            workspace.delete()

        raise SystemExit(0)
