from django.db import models
from django.db.models import Sum, Count, Q
from django.db.models.functions import Coalesce

from apps.authentication.models import Organization
from apps.authentication.services.service import get_all_org_child
from apps.core.services.filter.search import DynamicSearchService
from apps.product.models import OrganizationQuotaStats


class QuotaDashboardService:
    """
    dashboard of quota information
    """

    @staticmethod
    def get_dashboard(self, org: Organization, start_date: str = None, end_date: str = None,
                      search_fields: list[str] = None):
        orgs_child = get_all_org_child(org=org)
        orgs_child.append(org)

        if org.type.key == 'ADM':
            org_quota_stats = OrganizationQuotaStats.objects.all()
        else:
            org_quota_stats = OrganizationQuotaStats.objects.filter(
                organization__in=orgs_child
            )

        # filter queryset (transactions & items) by date
        if start_date and end_date:
            org_quota_stats = DynamicSearchService(
                queryset=org_quota_stats,
                start=start_date,
                end=end_date,
                date_field="create_date",
                search_fields=search_fields
            ).apply()

        org_quota_stats = org_quota_stats.aggregate(
            total_quotas=Count("quota", distinct=True),
            total_distributed=Coalesce(Sum("total_distributed", ), 0),
            remaining_amount=Coalesce(Sum("remaining_amount", ), 0),
            inventory_received=Coalesce(Sum("inventory_received", ), 0),
            sold_amount=Coalesce(Sum("sold_amount", ), 0),
            total_amount=Coalesce(Sum("total_amount", ), 0),
            inventory_entry_balance=Coalesce(Sum("inventory_entry_balance", ), 0),
        )

        return {
            "quotas_summary": org_quota_stats,
        }

    @staticmethod
    def get_dashboard_by_product(self, organization: Organization, products: list[int]):

        stat_by_prod = []
        for prod in products:
            org_quota_stat = OrganizationQuotaStats.objects.filter(
                organization=organization,
                quota__product_id=prod
            )
            product_stat_data = org_quota_stat.aggregate(
                quotas_count=Count('id'),
                total_quotas_weight=models.Sum('total_amount'),
                active_quotas_weight=models.Sum('active_quotas_weight', filter=Q(quota__is_closed=False)),
                closed_quotas_weight=models.Sum('closed_quotas_weight', filter=Q(quota__is_closed=True)),
                total_remaining_quotas_weight=models.Sum('remaining_amount'),
                total_distributed=models.Sum('quota_distributed'),
                total_warehouse_entry=models.Sum('inventory_received'),
                total_sold=models.Sum('total_sold'),
            )

            stat_by_prod.append(product_stat_data)

        return stat_by_prod
