# Copyright 2023 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 create workspaces."""

from datetime import timedelta

from django.core.exceptions import ValidationError
from django.core.management import CommandError

from debusine.artifacts.models import SINGLETON_COLLECTION_CATEGORIES
from debusine.db.context import context
from debusine.db.models import Collection, FileStore, Scope, Workspace
from debusine.django.management.debusine_base_command import DebusineBaseCommand


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

    help = "Create a new workspace"

    def add_arguments(self, parser):
        """Add CLI arguments for the create_workspace command."""
        parser.add_argument(
            "scope_workspace",
            metavar="scope/name",
            help="scope/name for new workspace",
        )
        parser.add_argument(
            "--public",
            action="store_true",
            help="Public permissions (default: private)",
        )
        parser.add_argument(
            "--default-expiration-delay",
            action="store",
            type=int,
            metavar="N",
            help="Minimal time (in days) that a new artifact is kept in the"
            " workspace before being expired (default: 0)",
        )
        parser.add_argument(
            "--default-file-store",
            metavar="NAME",
            help="Name of the default file store to use for this workspace",
        )
        parser.add_argument(
            "--no-singleton-collections",
            dest="singleton_collections",
            action="store_false",
            help=(
                "Don't create the usual singleton collections for this "
                "workspace (default: create singleton collections)"
            ),
        )

    @context.disable_permission_checks()
    def handle(self, scope_workspace: str, *args, **options):
        """Create the workspace."""
        scope_name, workspace_name = scope_workspace.split("/", 1)
        try:
            scope = Scope.objects.get(name=scope_name)
            workspace = Workspace(
                name=workspace_name,
                default_file_store=FileStore.default(),
                scope=scope,
            )
            if options["public"]:
                workspace.public = True
            if options["default_expiration_delay"]:
                workspace.default_expiration_delay = timedelta(
                    days=options["default_expiration_delay"]
                )
            if options["default_file_store"]:
                workspace.default_file_store = FileStore.objects.get(
                    name=options["default_file_store"]
                )
            workspace.full_clean()
            workspace.save()
            if options["singleton_collections"]:
                for category in SINGLETON_COLLECTION_CATEGORIES:
                    Collection.objects.create_singleton(category, workspace)
        except ValidationError as exc:
            raise CommandError(
                "Error creating workspace: " + "\n".join(exc.messages),
                returncode=3,
            )
        except FileStore.DoesNotExist:
            raise CommandError(
                f'File store "{options["default_file_store"]}" not found',
                returncode=3,
            )
        except Scope.DoesNotExist:
            raise CommandError(
                f'Scope "{scope_name}" not found',
                returncode=3,
            )

        raise SystemExit(0)
