from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import gettext as _
from rest_framework import serializers
from saas_base.drf.serializers import ModelSerializer, RelatedSerializerField
from saas_base.models import Member, UserEmail, Invitation
from saas_base.registry import perm_registry
from .tenant import TenantSerializer
from .user import SimpleUserSerializer
from .group import GroupSerializer


class InvitationSerializer(ModelSerializer):
    email = serializers.EmailField(required=True)
    role = serializers.CharField(required=False)
    groups = RelatedSerializerField(GroupSerializer, many=True, required=False)

    class Meta:
        model = Invitation
        exclude = ['tenant', 'inviter']
        read_only_fields = ['status', 'accepted_at', 'created_at']
        request_include_fields = ['groups']

    def validate_role(self, role: str):
        if role not in perm_registry.get_role_codes():
            raise serializers.ValidationError(_('Invalid role.'))
        return role

    def validate_email(self, email: str):
        request = self.context['request']
        if Invitation.objects.filter(tenant_id=request.tenant_id, email=email).count():
            raise serializers.ValidationError(_('This email has already been invited.'))

        try:
            user_email = UserEmail.objects.get_by_email(email)
        except ObjectDoesNotExist:
            return email

        if Member.objects.filter(tenant_id=request.tenant_id, user_id=user_email.user_id).count():
            raise serializers.ValidationError(_('This user has already been invited.'))

        return email


class InvitationInfoSerializer(ModelSerializer):
    tenant = TenantSerializer(read_only=True)
    inviter = SimpleUserSerializer(read_only=True)

    class Meta:
        model = Invitation
        fields = '__all__'
