from apps.calls.models import UserMessage


class MessageRepository:

    @staticmethod
    def base_queryset():
        return (
            UserMessage.objects
            .select_related("recipient", "recipient__profile")
            .only(
                "id",
                "customer_name",
                "body",
                "is_read",
                "read_at",
                "created_at",
                "recipient_id",
            )
        )

    @staticmethod
    def list_for_user(user, company):
        return MessageRepository.base_queryset().filter(
            recipient=user,
            company=company,
        )

    @staticmethod
    def unread_for_user(user):
        return MessageRepository.base_queryset().filter(
            recipient=user,
            is_read=False
        )

    @staticmethod
    def get_by_id(msg_id, user):
        return (
            MessageRepository.base_queryset()
            .filter(id=msg_id, recipient=user)
            .first()
        )

    @staticmethod
    def mark_as_read(instance):
        if instance is None:
            return None
        instance.mark_as_read()
        return instance

    @staticmethod
    def create_message(
            recipient,
            company,
            customer_name=None,
            customer_number=None,
            subject="",
            body="",
            twilio_call_sid=None,
    ):
        if twilio_call_sid is None:
            return UserMessage.objects.create(
                recipient=recipient,
                company=company,
                customer_name=customer_name,
                customer_number=customer_number,
                subject=subject,
                body=body,
            )

        message, _ = UserMessage.objects.update_or_create(
            twilio_call_sid=twilio_call_sid,
            defaults={
                'recipient': recipient,
                'company': company,
                'customer_name': customer_name,
                'customer_number': customer_number,
                'subject': subject,
                'body': body,
            }
        )

        return message

