from rest_framework.serializers import ModelSerializer, SerializerMethodField
from apps.accounts.models import Role, User, Organization, Invite

class UserSerializer(ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'uuid', 'email_address', 'first_name', 'last_name', 'date_of_birth', 'is_staff', 'is_manager', 'created_at', 'updated_at']
        read_only_fields = ['id', 'uuid', 'is_staff', 'created_at', 'updated_at']

class OrganizationSerializer(ModelSerializer):
    owner        = UserSerializer(read_only = True)
    member_count = SerializerMethodField()
    role_count   = SerializerMethodField()

    class Meta:
        model = Organization
        fields = ['id', 'uuid', 'name', 'description', 'owner', 'created_at', 'updated_at', 'member_count', 'role_count']
        read_only_fields = ['uuid', 'owner', 'created_at', 'updated_at']

    def get_member_count(self, obj):
        return obj.members.count()

    def get_role_count(self, obj):
        return obj.roles.count()

class InviteSerializer(ModelSerializer):
    organization = OrganizationSerializer(read_only = True)
    created_by = UserSerializer(read_only = True)
    invite_url = SerializerMethodField()
    is_valid   = SerializerMethodField()

    class Meta:
        model = Invite
        fields = ['id', 'uuid', 'organization', 'created_by', 'expires_at', 'uses', 'max_uses', 'is_active', 'created_at', 'updated_at', 'invite_url', 'is_valid']
        read_only_fields = ['id', 'uuid', 'organization', 'created_by', 'created_at', 'updated_at']

    def get_invite_url(self, obj: Invite) -> str:
        request = self.context.get('request')
        if request:
            return request.build_absolute_uri(f'/invite/{obj.uuid}')
        return f'/invite/{obj.uuid}'

    def get_is_valid(self, obj: Invite) -> bool:
        return obj.is_valid()

class RoleSerializer(ModelSerializer):
    organization = OrganizationSerializer(read_only = True)
    member_count = SerializerMethodField()

    class Meta:
        model = Role
        fields = ['id', 'uuid', 'name', 'description', 'organization', 'created_at', 'updated_at', 'member_count']
        read_only_fields = ['id', 'uuid', 'created_at', 'updated_at']

    def get_member_count(self, obj: Role):
        return obj.members.count()