from rest_framework import viewsets, permissions, generics
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from .models import Job, JobFavorite
from .serializers import JobListSerializer, JobDetailSerializer, JobFavoriteSerializer
from .filters import JobFilter
from apps.accounts.permissions import IsAdminOrSuperAdmin, IsSeeker


class JobPublicViewSet(viewsets.ReadOnlyModelViewSet):
    """公开只读，仅返回已发布职位"""
    queryset = Job.objects.filter(status='published').select_related('organization')
    filterset_class = JobFilter
    filter_backends = [DjangoFilterBackend, SearchFilter]
    search_fields = ['title', 'description', 'location']
    permission_classes = [permissions.AllowAny]

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return JobDetailSerializer
        return JobListSerializer

    @action(detail=True, methods=['post'], permission_classes=[IsSeeker])
    def favorite(self, request, pk=None):
        job = self.get_object()
        fav, created = JobFavorite.objects.get_or_create(user=request.user, job=job)
        if not created:
            fav.delete()
            return Response({'collected': False})
        return Response({'collected': True})


class MyFavoritesView(generics.ListAPIView):
    """求职者的收藏列表"""
    serializer_class = JobFavoriteSerializer
    permission_classes = [IsSeeker]

    def get_queryset(self):
        return JobFavorite.objects.filter(user=self.request.user).select_related(
            'job', 'job__organization'
        )


class JobManageViewSet(viewsets.ModelViewSet):
    """管理端：公司管理员管理本公司职位"""
    permission_classes = [IsAdminOrSuperAdmin]

    def get_serializer_class(self):
        if self.action in ['retrieve', 'create', 'update', 'partial_update']:
            return JobDetailSerializer
        return JobListSerializer

    def get_queryset(self):
        user = self.request.user
        if user.is_superadmin:
            return Job.objects.all().select_related('organization')
        # 防御 organization 为空的情况
        if not user.organization_id:
            return Job.objects.none()
        return Job.objects.filter(organization=user.organization).select_related('organization')

    def perform_create(self, serializer):
        if self.request.user.is_admin:
            # Admin 强制使用自己公司，忽略请求体中的 organization_id
            serializer.save(organization=self.request.user.organization)
        else:
            # 超管需要在请求体中提供 organization_id
            serializer.save()
