from rest_framework import generics, viewsets
from .models import Application
from .serializers import ApplicationCreateSerializer, ApplicationSerializer, ApplicationStatusSerializer
from .emails import notify_status_change
from apps.accounts.permissions import IsSeeker, IsAdminOrSuperAdmin

class ApplyView(generics.CreateAPIView):
    serializer_class = ApplicationCreateSerializer
    permission_classes = [IsSeeker]

class MyApplicationsView(generics.ListAPIView):
    serializer_class = ApplicationSerializer
    permission_classes = [IsSeeker]

    def get_queryset(self):
        return Application.objects.filter(applicant=self.request.user).select_related('job__organization')

class ApplicationManageViewSet(viewsets.ReadOnlyModelViewSet):
    """HR 查看本公司投递"""
    serializer_class = ApplicationSerializer
    permission_classes = [IsAdminOrSuperAdmin]

    def get_queryset(self):
        user = self.request.user
        if user.is_superadmin:
            return Application.objects.all().select_related('job__organization', 'applicant')
        return Application.objects.filter(
            job__organization=user.organization
        ).select_related('job__organization', 'applicant')


class ApplicationStatusUpdateView(generics.UpdateAPIView):
    serializer_class = ApplicationStatusSerializer
    permission_classes = [IsAdminOrSuperAdmin]

    def get_queryset(self):
        user = self.request.user
        if user.is_superadmin:
            return Application.objects.all()
        return Application.objects.filter(job__organization=user.organization)

    def perform_update(self, serializer):
        instance = serializer.save()
        notify_status_change(instance)
