from django.db.models import Q
from rest_framework import status
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet

from apps.accounts.models import Role
from apps.knowledge.models import RoleRagDocument, TrainingFile
from apps.knowledge.serializers import RoleRagDocumentSerializer, TrainingFileSerializer


class TrainingFileViewSet(ModelViewSet):
    queryset = TrainingFile.objects.all()
    serializer_class = TrainingFileSerializer
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]
    lookup_field = 'uuid'
    
    filterset_fields = {
        'role__organization__uuid': ['exact'],
        'role__uuid': ['exact'],
    }

    def get_queryset(self):
        user = self.request.user
        return TrainingFile.objects.filter(
            Q(role__organization__owner=user) |
            Q(role__organization__members=user)
        ).distinct()

    def perform_create(self, serializer):
        role_uuid = self.request.data.get('role')

        try:
            role = Role.objects.get(uuid=role_uuid)
        except Role.DoesNotExist:
            return Response({'error': 'Role not found'}, status=status.HTTP_404_NOT_FOUND)

        is_owner = role.organization.owner == self.request.user
        is_member = role.organization.members.filter(uuid=self.request.user.uuid).exists()

        if not (is_owner or is_member):
            return Response({'error': 'Permission denied'}, status=status.HTTP_403_FORBIDDEN)

        serializer.save(
            uploaded_by=self.request.user,
            role=role,
            file_name=self.request.FILES['file'].name,
            file_size=self.request.FILES['file'].size,
            file_type=self.request.FILES['file'].content_type
        )

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        is_uploader = instance.uploaded_by == request.user
        is_org_owner = instance.role.organization.owner == request.user

        if not (is_uploader or is_org_owner or request.user.is_manager):
            return Response({'error': 'Permission denied'}, status=status.HTTP_403_FORBIDDEN)

        return super().destroy(request, *args, **kwargs)


class RoleRagDocumentViewSet(ReadOnlyModelViewSet):
    queryset = RoleRagDocument.objects.all()
    serializer_class = RoleRagDocumentSerializer
    permission_classes = [IsAuthenticated]
    lookup_field = 'uuid'
    
    filterset_fields = {
        'role__organization__uuid': ['exact'],
        'role__uuid': ['exact'],
    }

    def get_queryset(self):
        user = self.request.user
        return RoleRagDocument.objects.filter(
            Q(role__organization__owner=user) |
            Q(role__organization__members=user)
        ).distinct()
