from rest_framework import serializers

from ichec_django_core.serializers.core import SERIALIZER_BASE_FIELDS

from marinerg_test_access.models import (
    AccessApplicationFacilityReview,
    AccessApplicationBoardReview,
    AccessApplicationBoardDecision,
)


class AccessApplicationFacilityReviewSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = AccessApplicationFacilityReview
        fields = SERIALIZER_BASE_FIELDS + (
            "confirmed_preapplication_discussion",
            "confirmed_app_info_in_line_with_discussion",
            "supporting_comments",
            "supporting_documents",
            "application",
            "facility",
        )


class AccessApplicationBoardReviewSerializer(serializers.HyperlinkedModelSerializer):

    supporting_document = serializers.HyperlinkedIdentityField(
        read_only=True, view_name="accessapplicationboardreview-supporting_document"
    )

    class Meta:
        model = AccessApplicationBoardReview
        fields = SERIALIZER_BASE_FIELDS + (
            "decision",
            "comments",
            "reviewer",
            "application",
            "supporting_document",
        )
        read_only_fields = SERIALIZER_BASE_FIELDS + ("reviewer", "supporting_document")

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if not instance.supporting_document:
            rep["supporting_document"] = None
        return rep

    def _is_reviewer(self, application) -> bool:
        request = self.context.get("request", None)

        for reviewer in application.call.board_members.all():
            if reviewer.id == request.user.id:
                return True
        return False

    def _already_submitted(self, application) -> bool:
        request = self.context.get("request", None)
        return (
            AccessApplicationBoardReview.objects.filter(
                application__id=application.id, reviewer__id=request.user.id
            ).count()
            > 0
        )

    def create(self, validated_data):

        if not self._is_reviewer(validated_data["application"]):
            raise serializers.ValidationError(
                {"reviewer": "You are not permitted to review to this application"}
            )

        if self._already_submitted(validated_data["application"]):
            raise serializers.ValidationError(
                {"reviewer": "You have already submitted a review for this application"}
            )

        return super().create(validated_data)


class AccessApplicationBoardDecisionSerializer(serializers.HyperlinkedModelSerializer):

    supporting_document = serializers.HyperlinkedIdentityField(
        read_only=True, view_name="accessapplicationboarddecision-supporting_document"
    )

    class Meta:
        model = AccessApplicationBoardDecision
        fields = SERIALIZER_BASE_FIELDS + (
            "decision",
            "comments",
            "reviewer",
            "application",
            "supporting_document",
            "selected_facility",
        )
        read_only_fields = SERIALIZER_BASE_FIELDS + ("reviewer", "supporting_document")

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if not instance.supporting_document:
            rep["supporting_document"] = None
        return rep

    def _is_chair(self, application) -> bool:
        request = self.context.get("request", None)
        return application.call.board_chair.id == request.user.id

    def _already_submitted(self, application) -> bool:
        request = self.context.get("request", None)
        return (
            AccessApplicationBoardDecision.objects.filter(
                application__id=application.id, reviewer__id=request.user.id
            ).count()
            > 0
        )

    def create(self, validated_data):

        if not self._is_chair(validated_data["application"]):
            raise serializers.ValidationError(
                {"reviewer": "You are not permitted to review to this application"}
            )

        if self._already_submitted(validated_data["application"]):
            raise serializers.ValidationError(
                {"reviewer": "You already submitted a decision for this application"}
            )

        return super().create(validated_data)
