from django.shortcuts import render

# Create your views here.
from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import CustomTokenObtainPairSerializer

class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer



from django.contrib.auth import get_user_model
CustomUser = get_user_model()

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser, DjangoModelPermissions
from django.db.models import Sum, F
from django.shortcuts import get_object_or_404

from .serializers import UserSerializer
# --- Permissions (Custom if needed) ---
# Example custom permission: Only an employee can view their own data
class IsOwnerOrAdmin(DjangoModelPermissions):
    """
    Custom permission to only allow owners of an object or an admin to view/edit it.
    Assumes the model instance has an 'employee' field that links to an Employee object,
    which in turn links to a CustomUser.
    """
    def has_object_permission(self, request, view, obj):
        if request.user.is_superuser or request.user.is_staff:
            return True
        # Check if the object belongs to the requesting user's employee profile
        if hasattr(obj, 'employee') and request.user.employee_profile == obj.employee:
            return True
        return False

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = CustomUser.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]


    def get_queryset(self):
        """
        Allow users to only see their own profile unless they are staff/admin.
        """
        if self.request.user.is_superuser or self.request.user.is_staff:
            return CustomUser.objects.all()
        return CustomUser.objects.filter(id=self.request.user.id)


    @action(detail=False, methods=['get'], url_path='me')
    def get_current_user_profile(self, request):
        """
        Retrieve the profile of the currently authenticated user.
        """
        serializer = self.get_serializer(request.user)
        return Response(serializer.data)




