"""Management command tests."""

from decimal import Decimal
from io import StringIO
from unittest.mock import patch

from django.core.management import call_command
from django.test import TestCase

from shop.models import JITA_SELL_PCT, HullListing, Shop
from shop.tests._corptools import make_asset, make_owner_character, make_ship_type


class RefreshPricesCommandTests(TestCase):
    def setUp(self):
        self.user, self.char = make_owner_character()
        self.ship = make_ship_type()
        self.shop = Shop.objects.create(slug="s", name="S", created_by=self.user)

    @patch("shop.tasks.jita_prices")
    def test_refresh_updates_pct_listing(self, mock_jp):
        mock_jp.return_value = {"buy": 100, "sell": 200}
        listing = HullListing.objects.create(
            shop=self.shop,
            eve_type=self.ship,
            price_mode=JITA_SELL_PCT,
            price_pct=Decimal("90"),
            price=0,
        )
        call_command("shop_refresh_prices", stdout=StringIO())
        listing.refresh_from_db()
        self.assertEqual(listing.price, 180)  # 90% of sell 200

    @patch("shop.tasks.jita_prices")
    def test_no_pct_listings_is_noop(self, mock_jp):
        out = StringIO()
        call_command("shop_refresh_prices", stdout=out)
        mock_jp.assert_not_called()
        self.assertIn("No", out.getvalue())


from shop.models import AUTO_STOCK, HULL, ShopSource  # noqa: E402


class RefreshStockCommandTests(TestCase):
    def setUp(self):
        self.user, self.char = make_owner_character()
        self.ship = make_ship_type()
        self.station = 60003760
        self.shop = Shop.objects.create(slug="s", name="S", created_by=self.user)
        ShopSource.objects.create(
            shop=self.shop,
            section=HULL,
            character_audit=self.char,
            location_id=self.station,
        )
        make_asset(
            self.char,
            type_id=self.ship.id,
            item_id=1,
            location_id=self.station,
            quantity=5,
        )

    def test_sync_recomputes(self):
        listing = HullListing.objects.create(
            shop=self.shop, eve_type=self.ship, stock_mode=AUTO_STOCK, stock=0
        )
        call_command("shop_refresh_stock", stdout=StringIO())
        listing.refresh_from_db()
        self.assertEqual(listing.stock, 5)

    def test_no_auto_shops_is_noop(self):
        # No hull source and no auto listings -> nothing to recompute.
        ShopSource.objects.filter(shop=self.shop, section=HULL).delete()
        out = StringIO()
        call_command("shop_refresh_stock", stdout=out)
        self.assertIn("No shops", out.getvalue())
