"""Blueprint mirror upsert tests (ESI fetch is mocked)."""

from django.test import TestCase

from shop.models import CharacterBlueprint
from shop.sections.bpc.blueprints import store_blueprints
from shop.tests._corptools import make_owner_character


class StoreBlueprintsTests(TestCase):
    def setUp(self):
        self.user, self.char = make_owner_character()

    def _row(self, item_id, me=10, te=20, runs=50, type_id=12040, quantity=-2):
        return {
            "item_id": item_id,
            "type_id": type_id,
            "material_efficiency": me,
            "time_efficiency": te,
            "runs": runs,
            "quantity": quantity,
        }

    def test_upsert_creates_and_updates(self):
        store_blueprints(self.char, [self._row(1), self._row(2, me=0, te=0, runs=1)])
        self.assertEqual(CharacterBlueprint.objects.count(), 2)
        bp = CharacterBlueprint.objects.get(item_id=1)
        self.assertEqual((bp.me, bp.te, bp.runs), (10, 20, 50))
        store_blueprints(self.char, [self._row(1, me=5)])
        bp.refresh_from_db()
        self.assertEqual(bp.me, 5)

    def test_stale_rows_pruned(self):
        store_blueprints(self.char, [self._row(1), self._row(2)])
        store_blueprints(self.char, [self._row(1)])
        self.assertEqual(
            set(CharacterBlueprint.objects.values_list("item_id", flat=True)), {1}
        )
