from django.db.models import Count, Avg, Q
from apps.calls.repositories import TonyCallRepository
from django.utils import timezone

class TonyCallService:
    """
    Business logic for TonyCall endpoints.
    """

    def __init__(self, user=None):
        self.user = user

    def scope_queryset_to_user(self, qs):
        """
        Apply company scoping: superuser sees all, others see only active_company.
        """
        if self.user is None:
            return qs.none()

        if self.user.is_superuser:
            return qs

        active_company = getattr(self.user, "active_company", None)

        if active_company:
            return qs.filter(company=active_company)
        return qs.none()

    def summarize(self, qs):
        """
        Compute a small summary for list filtering results.
        """
        data = qs.aggregate(
            total_calls=Count("id"),
            avg_booking_to_call_seconds=Avg("booking_datetime")  # placeholder: adjust if needed
        )
        return {
            "total_calls": data.get("total_calls") or 0,
        }
