"""Corp BPC stock + handler tests (ME/TE/runs come off the corptools asset)."""

from django.test import TestCase

from shop.models import BPC, BpcVariant, Shop, ShopSource
from shop.sections.bpc.stock import recompute_bpc_stock
from shop.tests._corptools import (
    make_corp_asset,
    make_corp_division,
    make_corp_owner,
    make_ship_type,
)

DIVISION = -600037601
OFFICE = 700000001


class CorpBpcRecomputeTests(TestCase):
    def setUp(self):
        self.user, self.corp = make_corp_owner()
        self.bp_type = make_ship_type(type_id=12040, name="Rifter Blueprint")
        self.shop = Shop.objects.create(
            slug="cb",
            name="CB",
            created_by=self.user,
            shop_type=Shop.ShopType.CORPORATION,
        )
        make_corp_division(self.corp, location_id=DIVISION)
        ShopSource.objects.create(
            shop=self.shop,
            section=BPC,
            corporation_audit=self.corp,
            location_id=DIVISION,
        )

    def _copy(self, item_id, me, te, runs):
        make_corp_asset(
            self.corp,
            type_id=self.bp_type.id,
            item_id=item_id,
            location_id=OFFICE,
            division_location_id=DIVISION,
            blueprint_copy=True,
            material_efficiency=me,
            time_efficiency=te,
            runs=runs,
        )

    def test_corp_copies_group_into_variants(self):
        self._copy(1, me=10, te=20, runs=50)
        self._copy(2, me=10, te=20, runs=50)  # same variant -> stock 2
        self._copy(3, me=0, te=0, runs=1)  # different variant
        recompute_bpc_stock(self.shop)
        variants = {
            (v.me, v.te, v.runs): v.stock
            for v in BpcVariant.objects.filter(listing__shop=self.shop)
        }
        self.assertEqual(variants, {(10, 20, 50): 2, (0, 0, 1): 1})

    def test_unresolvable_copy_ignored(self):
        make_corp_asset(
            self.corp,
            type_id=self.bp_type.id,
            item_id=9,
            location_id=OFFICE,
            division_location_id=DIVISION,
            blueprint_copy=True,
        )
        recompute_bpc_stock(self.shop)
        self.assertEqual(BpcVariant.objects.filter(listing__shop=self.shop).count(), 0)


from unittest.mock import patch  # noqa: E402

from shop.sections.bpc.handler import BpcSectionHandler  # noqa: E402


class CorpBpcHandlerTests(TestCase):
    def setUp(self):
        self.user, self.corp = make_corp_owner()
        self.shop = Shop.objects.create(
            slug="ch",
            name="CH",
            created_by=self.user,
            shop_type=Shop.ShopType.CORPORATION,
        )
        make_corp_division(self.corp, location_id=DIVISION)
        self.source = ShopSource.objects.create(
            shop=self.shop,
            section=BPC,
            corporation_audit=self.corp,
            location_id=DIVISION,
        )

    def test_enqueue_source_refresh_forces_corp_asset_pull(self):
        with patch("corptools.tasks.corporation.update_corp_assets.apply_async") as mc:
            returned = BpcSectionHandler().enqueue_source_refresh()
        self.assertTrue(mc.called)
        corp_id = self.corp.corporation.corporation_id
        self.assertIn(corp_id, returned)
        self.assertEqual(mc.call_args.kwargs["kwargs"], {"force_refresh": True})


from django.urls import reverse  # noqa: E402


class CorpBpcPipelineTests(TestCase):
    def setUp(self):
        from allianceauth.tests.auth_utils import AuthUtils
        from django.contrib.auth.models import User

        self.user, self.corp = make_corp_owner()
        AuthUtils.add_permission_to_user_by_name("shop.basic_access", self.user)
        AuthUtils.add_permission_to_user_by_name(
            "shop.manage_corporation_shops", self.user
        )
        self.user = User.objects.get(pk=self.user.pk)
        self.bp_type = make_ship_type(type_id=12040, name="Rifter Blueprint")
        self.shop = Shop.objects.create(
            slug="cbp",
            name="CBP",
            created_by=self.user,
            shop_type=Shop.ShopType.CORPORATION,
            corporation=self.corp.corporation,
        )
        self.shop.enabled_sections = [BPC]
        self.shop.save()
        make_corp_division(self.corp, location_id=DIVISION)

    def test_add_corp_bpc_stockroom_builds_variants(self):
        make_corp_asset(
            self.corp,
            type_id=self.bp_type.id,
            item_id=1,
            location_id=OFFICE,
            division_location_id=DIVISION,
            blueprint_copy=True,
            material_efficiency=10,
            time_efficiency=20,
            runs=50,
        )
        self.client.force_login(self.user)
        resp = self.client.post(
            reverse("backoffice:add_stockroom", args=[self.shop.pk, "bpc"]),
            {
                "owner_id": self.corp.pk,
                "location_id": DIVISION,
                "container_item_id": "",
            },
            SERVER_NAME="localhost",
        )
        self.assertRedirects(
            resp, reverse("backoffice:manage_section", args=[self.shop.pk, "bpc"])
        )
        source = self.shop.sources.get(section=BPC)
        self.assertEqual(source.corporation_audit_id, self.corp.pk)
        variant = BpcVariant.objects.get(listing__shop=self.shop)
        self.assertEqual(
            (variant.me, variant.te, variant.runs, variant.stock), (10, 20, 50, 1)
        )
