# Generated by Django 3.1.7 on 2023-10-18 09:19

from django.db import migrations
from django.db.models import Q, Sum

from thunderstore.community.consts import PackageListingReviewStatus


def create_missing(Community, CommunityAggregatedFields):
    communities = Community.objects.filter(aggregated_fields=None).order_by("pk")

    created_afs = CommunityAggregatedFields.objects.bulk_create(
        [CommunityAggregatedFields() for _ in range(communities.count())],
    )

    for community, aggregated_fields in zip(communities, created_afs):
        community.aggregated_fields = aggregated_fields

    Community.objects.bulk_update(communities, ["aggregated_fields"])


def update_for_community(community):
    listings = community.package_listings.exclude(package__is_active=False).exclude(
        ~Q(package__versions__is_active=True)
    )

    if community.require_package_listing_approval:
        listings = listings.exclude(
            ~Q(review_status=PackageListingReviewStatus.approved)
        )

    community.aggregated_fields.package_count = listings.count()
    community.aggregated_fields.download_count = sum(
        listing.package.versions.aggregate(downloads=Sum("downloads"))["downloads"]
        for listing in listings
    )
    community.aggregated_fields.save()


def forwards(apps, schema_editor):
    Community = apps.get_model("community", "Community")
    CommunityAggregatedFields = apps.get_model("community", "CommunityAggregatedFields")

    # Create CommunityAggregatedFields for Communities that have none.
    create_missing(Community, CommunityAggregatedFields)

    # Set initial values for aggregated fields
    for community in Community.objects.all():
        update_for_community(community)


class Migration(migrations.Migration):

    dependencies = [
        ("community", "0024_add_community_aggregated_fields"),
    ]

    operations = [
        migrations.RunPython(forwards, migrations.RunPython.noop),
    ]
