"""Hull stock: recompute stored quantities from corptools assets."""

from ...sources import source_assets

SHIP_CATEGORY_ID = 6


def ship_type_ids_in_source(source):
    """Distinct ship-category type ids at a source (for auto-listing). Category is
    resolved via eve_sde (complete, no ESI); the caller stores an eveuniverse
    EveType for each returned id."""
    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=SHIP_CATEGORY_ID
        ).values_list("id", flat=True)
    )


def recompute_shop_stock(shop) -> None:
    """Recompute stored stock for every hull listing, then drop auto-stock
    listings that fell to 0 and are not marked persist (listing = what's in stock)."""
    from ...models import AUTO_STOCK

    to_delete = []
    for listing in shop.hull_listings.all():
        listing.recompute_stock()
        if (
            listing.stock_mode == AUTO_STOCK
            and listing.stock == 0
            and not listing.persist
        ):
            to_delete.append(listing.pk)
    if to_delete:
        shop.hull_listings.filter(pk__in=to_delete).delete()
