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

from ...sources import source_assets

SHIP_CATEGORY_ID = 6


def ship_type_ids_in_source(source):
    """Distinct ship-category EveType ids present at a source (for auto-listing)."""
    return list(
        source_assets(source)
        .filter(eve_type__eve_group__eve_category_id=SHIP_CATEGORY_ID)
        .values_list("eve_type_id", flat=True)
        .distinct()
    )


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()
