from apps.calls.models import Call
from apps.calls.constants import BotType
from apps.companies.constants import CompanyType


class CallsRepository:

    @staticmethod
    def get_queryset():
        return Call.objects.all()

    @staticmethod
    def get_calls_by_company(company_id):
        return CallsRepository.get_queryset().filter(
            company_id=company_id
        ).order_by("-created_at")

    @staticmethod
    def get_calls_by_bot(bot_type, company_id=None):
        return CallsRepository.get_queryset().filter(
            company_id=company_id,
            bot_type=bot_type
        ).order_by("-created_at") if company_id else (
            CallsRepository.get_queryset().filter(
            bot_type=bot_type
        ))

    @staticmethod
    def get_sales_calls(company_id=None, filters=None):
        qs = CallsRepository.get_calls_by_bot(
            company_id=company_id,
            bot_type=BotType.SALES_BOT.value
        )

        if filters:
            qs = qs.filter(**filters)

        return qs.select_related("company").order_by("-id")

    @staticmethod
    def get_service_calls(company_id=None, filters=None):
        qs = CallsRepository.get_calls_by_bot(
            company_id=company_id,
            bot_type=BotType.SERVICE_BOT
        )

        if filters:
            qs = qs.filter(**filters)

        return qs.select_related("company").order_by("-id")

    @staticmethod
    def get_dealership_group_calls(company_id=None, **filters):
        qs = CallsRepository.get_calls_by_bot(
            company_id=company_id,
            bot_type=BotType.DEALERSHIP_GROUP_BOT
        )

        if filters:
            qs = qs.filter(**filters)

        return qs

    @staticmethod
    def get_dealership_calls(user, **filters):
        if user.is_superuser:
            return CallsRepository.get_dealership_group_calls(**filters)

        qs = None

        if user.active_company:
            if user.active_company.company_type == CompanyType.DEALERSHIP:
                qs = CallsRepository.get_queryset().filter(
                    dealership=user.active_company,
                    bot_type=BotType.DEALERSHIP_GROUP_BOT
                ).select_related("dealership").order_by("-id")
            elif user.active_company.company_type == CompanyType.DEALERSHIP_GROUP:
                qs = CallsRepository.get_dealership_group_calls(
                    company_id=user.active_company.id,
                    **filters
                ).select_related("company").order_by("-id")

        return qs
