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
from saas_base.registry import perm_registry
from saas_base.registry.checker import has_permission
from .group import GroupSerializer
from .user import UserSerializer


class MemberSerializer(ModelSerializer):
    user = UserSerializer(required=False, read_only=True)
    groups = serializers.SlugRelatedField(many=True, read_only=True, slug_field='name')
    permissions = serializers.SerializerMethodField()

    class Meta:
        model = Member
        exclude = ['tenant']
        request_include_fields = ['user', 'groups']

    def get_permissions(self, obj: Member):
        assigned_patterns = obj.get_all_permissions()

        all_registered_perms = perm_registry.get_permission_list()
        if obj.tenant.owner_id == obj.user_id:
            return [p.key for p in all_registered_perms]

        resolved_keys = [p.key for p in all_registered_perms if has_permission(p.key, assigned_patterns)]
        return resolved_keys


class MemberUpdateSerializer(ModelSerializer):
    groups = RelatedSerializerField(GroupSerializer, many=True)

    class Meta:
        model = Member
        fields = ['role', 'groups', 'permissions']

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

    def validate_permissions(self, perms: list[str]):
        registered_perms = perm_registry.get_permission_keys()
        for key in perms:
            if not has_permission(key, registered_perms):
                raise serializers.ValidationError(f'Permission {key} is not registered.')
        return perms
