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):
        return MessageRepository.base_queryset().filter(recipient=user)

    @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,
            customer_name=None,
            customer_number=None,
            subject="",
            body="",
    ):
        return UserMessage.objects.create(
            recipient=recipient,
            customer_name=customer_name,
            customer_number=customer_number,
            subject=subject,
            body=body,
        )
