"""Tests for the create_user_token management command."""

from io import StringIO

from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase

from mcp_server.models import UserToken

User = get_user_model()


class CreateUserTokenCommandTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="carol", email="carol@example.com", password="pw"
        )

    def test_create_basic_token(self):
        out = StringIO()
        call_command("create_user_token", user="carol@example.com", name="CLI", stdout=out)
        self.assertEqual(UserToken.objects.count(), 1)
        self.assertIn("CLI", out.getvalue())

    def test_lookup_by_username(self):
        out = StringIO()
        call_command("create_user_token", user="carol", name="CLI2", stdout=out)
        self.assertEqual(UserToken.objects.count(), 1)

    def test_unknown_user_raises(self):
        with self.assertRaises(CommandError):
            call_command("create_user_token", user="nobody@x.com", name="x")

    def test_inactive_user_raises(self):
        self.user.is_active = False
        self.user.save()
        with self.assertRaises(CommandError):
            call_command("create_user_token", user="carol", name="x")

    def test_tool_whitelist_parsed(self):
        out = StringIO()
        call_command(
            "create_user_token",
            user="carol",
            name="Restricted",
            tools="search,get_chunk",
            stdout=out,
        )
        token = UserToken.objects.get(name="Restricted")
        self.assertEqual(token.allowed_tools, ["search", "get_chunk"])
