# Copyright 2022 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 manage tokens."""

from django.core.management.base import CommandError

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


class Command(DebusineBaseCommand):
    """Command to manage tokens. E.g. enable and disable them."""

    help = 'Enables and disables tokens'

    def add_arguments(self, parser):
        """Add CLI arguments for the manage_token command."""
        parser.add_argument(
            'action',
            choices=['enable', 'disable'],
            help='Enable or disable the token',
        )
        parser.add_argument('token', help='Token key to modify')

    def handle(self, *args, **options):
        """Enable or disable the token."""
        token = Token.objects.get_token_or_none(options['token'])

        if token is None:
            raise CommandError('Token not found', returncode=3)

        action = options['action']

        if action == 'enable':
            token.enable()
        elif action == 'disable':
            token.disable()
        else:  # pragma: no cover
            pass  # never reached
