from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.db.models import Q
from rest_framework import filters
from rest_framework import viewsets
from rest_framework.exceptions import MethodNotAllowed

from api_core.permissions import IsCoreSuperAdmin
from api_core.serializers import (
    CoreGroupSerializer,
    CorePermissionSerializer,
    CoreUserSerializer,
)
from flower.viewsets import LimitedLimitOffsetPagination


User = get_user_model()


class CoreUserViewSet(viewsets.ModelViewSet):
    serializer_class = CoreUserSerializer
    permission_classes = [IsCoreSuperAdmin]
    pagination_class = LimitedLimitOffsetPagination
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ["username", "email", "first_name", "last_name", "employee__name"]
    ordering_fields = ["id", "username", "date_joined", "last_login"]
    ordering = ["id"]

    def get_queryset(self):
        merchant = getattr(self.request, "core_merchant", None)
        if merchant is None:
            return User.objects.none()
        return (
            User.objects.filter(
                Q(employee__merchant=merchant) | Q(profile__merchant=merchant)
            )
            .distinct()
            .prefetch_related("groups", "user_permissions__content_type")
            .select_related("employee", "profile")
            .order_by("id")
        )

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context["merchant"] = self.request.core_merchant
        return context

    def destroy(self, request, *args, **kwargs):
        raise MethodNotAllowed("DELETE", detail="Core users 不允许删除，请通过 is_active=false 停用")


class CoreGroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.prefetch_related("permissions__content_type").order_by("id")
    serializer_class = CoreGroupSerializer
    permission_classes = [IsCoreSuperAdmin]
    pagination_class = LimitedLimitOffsetPagination
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ["name"]
    ordering_fields = ["id", "name"]
    ordering = ["id"]


class CorePermissionViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Permission.objects.select_related("content_type").order_by(
        "content_type__app_label",
        "content_type__model",
        "codename",
    )
    serializer_class = CorePermissionSerializer
    permission_classes = [IsCoreSuperAdmin]
    pagination_class = LimitedLimitOffsetPagination
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ["name", "codename", "content_type__app_label", "content_type__model"]
    ordering_fields = ["id", "name", "codename"]

