# 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 django.core.management import CommandError
from django.db import IntegrityError

from debusine.db.models import FileStore, 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("name", help="Name")
        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",
        )

    def handle(self, *args, **options):
        """Create the workspace."""
        try:
            workspace = Workspace.objects.create_with_name(options["name"])
            if options["public"]:
                workspace.public = True
            if options["default_expiration_delay"]:
                workspace.default_expiration_delay = options[
                    "default_expiration_delay"
                ]
            if options["default_file_store"]:
                workspace.default_file_store = FileStore.objects.get(
                    name=options["default_file_store"]
                )
            workspace.save()
        except IntegrityError:
            raise CommandError(
                "A workspace with this name already exists",
                returncode=3,
            )
        except FileStore.DoesNotExist:
            raise CommandError(
                f'File store "{options["default_file_store"]}" not found',
                returncode=3,
            )

        raise SystemExit(0)
