"""Stock computation from memberaudit assets."""

from django.db.models import Sum

from memberaudit.models import CharacterAsset

SHIP_CATEGORY_ID = 6


def _source_assets(source):
    """Base queryset of the assets located at a single ShopSource."""
    qs = CharacterAsset.objects.filter(character_id=source.character_id)
    if source.container_item_id:
        return qs.filter(
            parent__character_id=source.character_id,
            parent__item_id=source.container_item_id,
        )
    return qs.filter(location_id=source.location_id, parent__isnull=True)  # station hangar


def source_qty(source, eve_type) -> int:
    """Quantity of `eve_type` available at a single source."""
    n = _source_assets(source).filter(eve_type=eve_type).aggregate(n=Sum("quantity"))["n"]
    return n or 0


def ship_type_ids_in_source(source):
    """Distinct ship-category EveType ids physically 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()
