from django.shortcuts import get_object_or_404
from rest_framework.views import APIView

from scrutiny.api import serializers
from scrutiny.api.utils import APIErrorBadRequest, Response
from scrutiny.projects.models import Project
from scrutiny.projects.views import IssuesMixin, ProjectSummaryHistoryMixin


class ProjectPendingIssues(ProjectSummaryHistoryMixin, IssuesMixin, APIView):
    serializer_class = serializers.ProjectPendingIssuesSerializer
    permission_classes = ()

    def get(self, request, project_identifier):
        self.object = get_object_or_404(Project, slug=project_identifier)

        serializer = self.serializer_class(data=request.query_params)
        if not serializer.is_valid():
            raise APIErrorBadRequest('invalid payload', errors=serializer.errors)
        data = serializer.validated_data

        last_version = self.get_future_version()
        if not last_version:
            return Response({'data': []})

        issues = self.get_pending_issues(last_version['modules'], user_id=data['user_id'])

        return Response(
            {
                'data': [
                    {
                        'id': issue.id,
                        'text': issue.subject,
                    }
                    for issue in issues
                ]
            }
        )


project_pending_issues = ProjectPendingIssues.as_view()
