import json
from datetime import datetime, timedelta

from django.http import HttpResponse
from django.utils.timezone import make_aware

from la_chariotte.accounts.models import CustomUser
from la_chariotte.order.models import GroupedOrder, Order


def stats(request):
    last_month = make_aware(datetime.today() - timedelta(days=30))

    last_month_grouped_orders = GroupedOrder.objects.filter(
        deadline__gte=last_month
    ).count()

    return HttpResponse(
        json.dumps(
            {
                "total_users": CustomUser.objects.count(),
                "total_grouped_orders": GroupedOrder.objects.count(),
                "total_orders": Order.objects.count(),
                "last_month_grouped_orders": last_month_grouped_orders,
            }
        ),
        content_type="application/json",
    )
