from django.contrib.auth import get_user_model
from django.core.management import BaseCommand
from django.db.models import Sum

from gaehsnitz.models import Drink
from gaehsnitz.templatetags.money import euro

User = get_user_model()


class Command(BaseCommand):
    def handle(self, *args, **options):
        id_to_name = {d.id: d.name for d in Drink.objects.all()}
        for user in User.objects.all().order_by("username"):
            to_pay = user.consumed_drinks_price
            if to_pay != 0:
                paid_consumption = user.consumption_list.filter(for_free=False)
                drink_list = []
                for drink_dict in paid_consumption.values("drink_id").annotate(amount=Sum("amount")):
                    name = id_to_name[drink_dict["drink_id"]]
                    amount = drink_dict["amount"]
                    drink_list.append(f"{amount}x {name}")
                print(f"{user.username.capitalize()}: {euro(to_pay)} ({', '.join(drink_list)})")
