from django.core.management.base import BaseCommand
from django.db import transaction

from apps.product.models import Quota, OrganizationQuotaStats


class Command(BaseCommand):
    help = "Ensure each Quota has exactly one OrganizationQuotaStats per related organization"

    @transaction.atomic
    def handle(self, *args, **options):
        quotas = Quota.objects.prefetch_related('assigned_organizations').select_related(
            'registerer_organization', 'product'
        ).all()

        created = 0
        existing = 0
        updated = 0
        merged = 0

        for quota in quotas:
            # create_org_stat_by_quota(quota)
            # create_org_stat_by_distribution(quota)
            update_quota_assigned_organizations(quota)


def create_org_stat_by_quota(quota: Quota):
    was_created = 0
    is_created = 0

    org_quota_stat, created = OrganizationQuotaStats.objects.get_or_create(
        quota=quota,
        organization=quota.registerer_organization,
        total_amount=quota.quota_weight,
        total_distributed=quota.quota_distributed,
        remaining_amount=quota.remaining_weight,
        free_sale_balance=quota.free_sale_balance,
        pre_sale_balance=quota.pre_sale_balance,
        stat_type='quota'
    )

    if created:
        is_created += 1
    else:
        was_created += 1

    print('is_created:', is_created, '\n', 'was_created:', was_created)


def create_org_stat_by_distribution(quota: Quota):
    main_stat = OrganizationQuotaStats.objects.get(quota=quota, stat_type="quota")
    distributions = quota.distributions_assigned.filter()

    was_created = 0
    created = 0

    for dist in distributions:
        org_quota_stat, created = OrganizationQuotaStats.objects.get_or_create(
            quota=quota,
            organization=dist.assigned_organization,
            total_amount=dist.weight,
            total_distributed=dist.distributed,
            remaining_amount=dist.remaining_weight,
            free_sale_balance=dist.free_sale_balance,
            pre_sale_balance=dist.pre_sale_balance,
            inventory_received=dist.warehouse_entry,
            inventory_entry_balance=dist.warehouse_balance,
            sold_amount=dist.been_sold,
            stat_type="distribution",
        )

        if created:
            created += 1
        else:
            was_created += 1

        main_stat.distributions.add(dist)

        print(org_quota_stat)

    print('created:', created, '\n', 'was_created:', was_created)


def update_quota_assigned_organizations(quota: Quota):
    distributions = quota.distributions_assigned.all()
    for dist in distributions:
        quota.assigned_organizations.add(dist.assigned_organization)
