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

"""Tests for the management command list_tokens."""
from datetime import timedelta

from django.contrib.auth import get_user_model
from django.test import TestCase

from debusine.db.models import Token
from debusine.server.management.commands.tests import call_command


class ListTokensCommandTests(TestCase):
    """Tests for the list_tokens command."""

    def test_list_tokens_no_filtering(self):
        """list_tokens print the token key."""
        user = get_user_model().objects.create_user(
            username="John", email="john@example.com"
        )
        token = Token.objects.create(user=user, comment='Test comment')

        stdout, stderr, _ = call_command('list_tokens')

        self.assertIn(token.hash, stdout)
        self.assertIn(token.user.username, stdout)
        self.assertIn(token.created_at.isoformat(), stdout)
        self.assertEqual(stdout.count(str(token.enabled)), 1)
        self.assertIn(token.comment, stdout)

    def test_list_tokens_filtered_by_username(self):
        """list_tokens print the correct filtered owners."""
        user = get_user_model().objects.create_user(
            username="John", email="john@example.com"
        )
        token_john = Token.objects.create(user=user)
        token_no_john = Token.objects.create()

        stdout, stderr, _ = call_command('list_tokens', '--username', 'John')

        self.assertIn(token_john.hash, stdout)
        self.assertNotIn(token_no_john.hash, stdout)

    def test_list_tokens_sorted_by_created_at(self):
        """Tokens are sorted by created_at."""
        user = get_user_model().objects.create_user(
            username="John", email="john@example.com"
        )
        token_1 = Token.objects.create(user=user)
        token_2 = Token.objects.create(user=user)

        stdout, _, _ = call_command('list_tokens')

        # token_1 is displayed before token2 (ordered by created_at)
        self.assertLess(stdout.index(token_1.hash), stdout.index(token_2.hash))

        # Make token_1.created_at later than token_2
        token_1.created_at = token_2.created_at + timedelta(minutes=1)
        token_1.save()

        stdout, _, _ = call_command('list_tokens')

        # Now token_1 appear after token_2
        self.assertGreater(
            stdout.index(token_1.hash), stdout.index(token_2.hash)
        )
