# 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 create file stores."""

import argparse

from django.core.exceptions import ValidationError
from django.core.management import CommandError
from django.db import IntegrityError, transaction

from debusine.db.models import FileStore
from debusine.server.management.debusine_base_command import DebusineBaseCommand


class Command(DebusineBaseCommand):
    """Command to create a file store."""

    help = "Create a new file store."

    def add_arguments(self, parser):
        """Add CLI arguments for the create_file_store command."""
        parser.add_argument("name", help="Name")
        parser.add_argument(
            "backend",
            help="Backend type",
            choices=dict(FileStore.BackendChoices.choices).keys(),
        )
        parser.add_argument(
            "--configuration",
            type=argparse.FileType("r"),
            help=(
                "File path (or - for stdin) to read the configuration for the "
                "file store. YAML format. Defaults to stdin."
            ),
            default="-",
        )

    def handle(self, *args, **options):
        """Create the file store."""
        name = options["name"]
        backend = options["backend"]
        configuration = (
            self.parse_yaml_data(options["configuration"].read()) or {}
        )

        with transaction.atomic():
            try:
                file_store = FileStore.objects.create(
                    name=name, backend=backend, configuration=configuration
                )
                file_store.full_clean()
            except ValidationError as exc:
                raise CommandError(
                    f"Error creating file store: {exc}", returncode=3
                )
            except IntegrityError:
                raise CommandError(
                    "A file store with this name already exists", returncode=3
                )

        raise SystemExit(0)
