from drf_spectacular.utils import extend_schema

from django.contrib.auth import get_user_model
from django.db.models import Prefetch, Q
from django.utils.translation import gettext

from rest_framework.permissions import IsAuthenticated

from lms.core.views.pagination import LimitOffsetAllPagination
from lms.core.views.viewsets import APIModelViewSet

from ..models import Mentorship
from ..serializers import UserColleagueDetailSerializer, UserColleagueListSerializer

User = get_user_model()


class UserColleagueViewSet(APIModelViewSet):
    """
    Коллеги пользователя (подчинённые и подопечные)
    """
    serializer_class = UserColleagueListSerializer
    serializer_classes = {
        'retrieve': UserColleagueDetailSerializer,
    }
    queryset = User.objects.filter(
        staffprofile__is_dismissed=False,
    ).select_related(
        'staffprofile'
    ).prefetch_related(
        'in_courses', 'in_courses__course_progresses',
        Prefetch(
            lookup='mentorships_as_mentee',
            queryset=Mentorship.objects.active().select_related('mentor'),
        ),
    ).order_by('id')

    permission_classes = [
        IsAuthenticated,
    ]
    pagination_class = LimitOffsetAllPagination

    def get_queryset(self):
        queryset = super().get_queryset()
        user = getattr(self.request, 'user')

        return queryset.filter(
            Q(mentorships_as_mentee__mentor_id=user.id, mentorships_as_mentee__is_active=True) |
            Q(staffprofile__head__user_id=user.id)
        )

    @extend_schema(
        summary=gettext("Список коллег пользователя (подчинённые и подопечные)"),
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

    @extend_schema(
        summary=gettext("Информация о коллеге пользователя (подчинённом или подопечном)"),
    )
    def retrieve(self, request, *args, **kwargs):
        return super().retrieve(request, *args, **kwargs)
