from django.db.models import Count, Sum, 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 Quota
from apps.warehouse.models import InventoryEntry


class InventoryEntryDashboardService:
    """
    Inventory Entry Dashboard Services
    """

    @staticmethod
    def get_dashboard(
            org: Organization,
            start_date: str = None,
            end_date: str = None,
            search_fields: list[str] = None,
            query_string: str = None
    ):
        """ dashboard of inventory entry page """

        child_orgs = get_all_org_child(org)
        child_orgs.append(org)

        if org.type.key == 'ADM':
            inventory_entries = InventoryEntry.objects.filter(quota__is_closed=False)

            # calculate quotas that have received inventory entry
            quotas = Quota.objects.filter(
                org_quota_stats__inventory_received__gt=0,
                is_closed=False,
            ).distinct('id')

        else:

            inventory_entries = InventoryEntry.objects.filter(
                quota__is_closed=False,
                organization__in=child_orgs
            )

            # calculate quotas that have received inventory entry
            quotas = Quota.objects.filter(
                Q(registerer_organization=org) |
                Q(assigned_organizations__in=child_orgs),
                org_quota_stats__inventory_received__gt=0,
                is_closed=False,
            ).distinct('id')

        if (start_date and end_date) or query_string:
            inventory_entries = DynamicSearchService(
                queryset=inventory_entries,
                start=start_date,
                end=end_date,
                search_fields=search_fields,
                date_field="create_date",
                query_string=query_string
            ).apply()
        print(inventory_entries)

        dashboard = inventory_entries.aggregate(
            total_entries=Count("id"),
            total_weight=Coalesce(Sum("weight"), 0),
        )

        dashboard.update(
            total_quotas=quotas.count(),
        )

        return dashboard
