"""BPC stock recompute: blueprint-copy assets join CharacterBlueprint -> variants."""

from django.test import TestCase

from shop.models import (
    BPC,
    BpcListing,
    BpcVariant,
    CharacterBlueprint,
    Shop,
    ShopSource,
)
from shop.sections.bpc.stock import recompute_bpc_stock
from shop.tests._corptools import make_asset, make_owner_character, make_ship_type

STATION = 60003760


class RecomputeBpcStockTests(TestCase):
    def setUp(self):
        self.user, self.audit = make_owner_character()
        self.bp_type = make_ship_type(type_id=12040, name="Rifter Blueprint")
        self.shop = Shop.objects.create(slug="s", name="S", created_by=self.user)
        ShopSource.objects.create(
            shop=self.shop,
            section=BPC,
            character_audit=self.audit,
            location_id=STATION,
        )

    def _copy(self, item_id, me, te, runs):
        make_asset(
            self.audit,
            type_id=self.bp_type.id,
            item_id=item_id,
            location_id=STATION,
            blueprint_copy=True,
        )
        CharacterBlueprint.objects.create(
            character=self.audit,
            item_id=item_id,
            type_id=12040,
            me=me,
            te=te,
            runs=runs,
            quantity=-2,
        )

    def test_groups_copies_into_variants(self):
        self._copy(1, 10, 20, 50)
        self._copy(2, 10, 20, 50)  # same variant -> stock 2
        self._copy(3, 0, 0, 1)  # different variant -> stock 1
        recompute_bpc_stock(self.shop)
        listing = BpcListing.objects.get(shop=self.shop, eve_type=self.bp_type)
        self.assertEqual(listing.variants.count(), 2)
        v = listing.variants.get(me=10, te=20, runs=50)
        self.assertEqual(v.stock, 2)

    def test_unresolvable_copy_excluded(self):
        make_asset(
            self.audit,
            type_id=self.bp_type.id,
            item_id=9,
            location_id=STATION,
            blueprint_copy=True,
        )
        recompute_bpc_stock(self.shop)
        self.assertFalse(BpcListing.objects.filter(shop=self.shop).exists())

    def test_price_preserved_across_recompute(self):
        self._copy(1, 10, 20, 50)
        recompute_bpc_stock(self.shop)
        v = BpcVariant.objects.get(me=10, te=20, runs=50)
        v.price = 5_000_000
        v.save(update_fields=["price"])
        self._copy(2, 10, 20, 50)
        recompute_bpc_stock(self.shop)
        v.refresh_from_db()
        self.assertEqual((v.stock, v.price), (2, 5_000_000))

    def test_empty_variant_removed(self):
        self._copy(1, 10, 20, 50)
        recompute_bpc_stock(self.shop)
        from corptools.models import CharacterAsset

        CharacterAsset.objects.filter(item_id=1).delete()
        recompute_bpc_stock(self.shop)
        self.assertFalse(BpcListing.objects.filter(shop=self.shop).exists())
