"""Module stock: which stocked types auto-list, and recompute stored quantities."""

from ...sources import source_assets

# eve_sde category ids: 7 Module (incl. rigs), 18 Drone, 20 Implant (+ boosters).
MODULE_CATEGORY_IDS = frozenset({7, 18, 20})


def module_type_ids_in_source(source):
    """Distinct allowlisted-category type ids at a source (for auto-listing).
    Category is resolved via eve_sde; the caller stores an eveuniverse EveType."""
    from eve_sde.models import ItemType

    type_ids = source_assets(source).values_list("type_id", flat=True).distinct()
    return list(
        ItemType.objects.filter(
            id__in=list(type_ids), group__category_id__in=MODULE_CATEGORY_IDS
        ).values_list("id", flat=True)
    )


def recompute_module_stock(shop) -> None:
    """Recompute each module listing's stock; drop any that fell to 0 (no persist)."""
    to_delete = []
    for listing in shop.module_listings.all():
        listing.recompute_stock()
        if listing.stock == 0:
            to_delete.append(listing.pk)
    if to_delete:
        shop.module_listings.filter(pk__in=to_delete).delete()
