from django.db.models import OuterRef, F, Value, Func
from django.db.models.functions import Coalesce
from apps.customers.models import Customer

class CustomerRepository:
    @staticmethod
    def get_name_subquery():
        """
        Returns a Subquery that fetches the customer's name by phone and company,
        falling back to 'Unknown' if name is empty or null.
        """
        subquery = Customer.objects.filter(
            company_id=OuterRef('company_id'),
            phone=OuterRef('from_number')
        ).annotate(
            name_or_unknown=Coalesce(
                Func(
                    F('name'),
                    function='NULLIF',
                    template="%(function)s(%(expressions)s, '')"
                ),
                Value("Unknown")
            )
        ).values('name_or_unknown')[:1]

        return subquery
