from django.core.management import call_command
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient

from api.models import Hero, Item


class RandomizeBuildAPITest(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.hero = Hero.objects.create(name="Axe", primary="Strength")
        Item.objects.bulk_create(
            [
                Item(name="Blink Dagger"),
                Item(name="Black King Bar"),
                Item(name="Boots of Travel"),
                Item(name="Force Staff"),
            ]
        )

    def test_randomize_with_skills(self):
        response = self.client.post(
            "/api/randomize",
            {"includeSkills": True, "includeAspect": False, "itemsCount": 3},
            format="json",
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()

        self.assertIn("hero", data)
        self.assertEqual(len(data.get("items", [])), 3)
        self.assertIn("skillBuild", data)
        self.assertTrue(data.get("skillBuilds"))
        self.assertNotIn("aspect", data)

    def test_randomize_with_aspect_only(self):
        response = self.client.post(
            "/api/randomize",
            {"includeSkills": False, "includeAspect": True, "itemsCount": 2},
            format="json",
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()

        self.assertIn("aspect", data)
        self.assertTrue(data.get("aspects"))
        self.assertNotIn("skillBuild", data)
        self.assertEqual(len(data.get("items", [])), 2)

    def test_rejects_invalid_payload(self):
        response = self.client.post(
            "/api/randomize",
            {"includeSkills": "yes", "includeAspect": True, "itemsCount": 0},
            format="json",
        )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn("message", response.json())


class LoadStaticDataCommandTest(TestCase):
    def test_loads_heroes_and_items(self):
        call_command("load_static_data")

        self.assertGreater(Hero.objects.count(), 0)
        self.assertGreater(Item.objects.count(), 0)
