from rest_framework import serializers
from saas_base.drf.serializers import FlattenModelSerializer
from saas_base.models import Member
from saas_base.registry import perm_registry
from saas_base.registry.checker import has_permission
from .tenant import TenantSerializer


class UserTenantSerializer(FlattenModelSerializer):
    tenant = TenantSerializer(required=True)
    groups = serializers.SlugRelatedField(many=True, read_only=True, slug_field='name')
    permissions = serializers.SerializerMethodField()
    member_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = Member
        exclude = ['user', 'id', 'created_at']
        flatten_fields = ['tenant']
        request_include_fields = ['groups', 'member_count']

    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
