from rest_framework import generics, permissions, parsers

from .serializers import AdminCreateUserSerializer, AdminUserSerializer, UserProfileSerializer
from django.contrib.auth import get_user_model

User = get_user_model()


class UserProfileView(generics.RetrieveUpdateAPIView):
    """GET / PATCH the authenticated user's profile (including avatar upload)."""
    serializer_class = UserProfileSerializer
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = [parsers.MultiPartParser, parsers.FormParser, parsers.JSONParser]

    def get_object(self):
        return self.request.user


class AdminUserListView(generics.ListCreateAPIView):
    """Admin: list all users (GET) or create a new user (POST)."""
    permission_classes = [permissions.IsAdminUser]
    queryset = User.objects.all().order_by('date_joined')

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return AdminCreateUserSerializer
        return AdminUserSerializer


class AdminUserDetailView(generics.RetrieveUpdateAPIView):
    """Admin: activate/deactivate or promote/demote a user."""
    serializer_class = AdminUserSerializer
    permission_classes = [permissions.IsAdminUser]
    queryset = User.objects.all()
