from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers

from apps.accounts.models import UserProfile
from apps.accounts.serializers import UserSerializer  # existing shared user serializer


class UserProfileCreateInputSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = "__all__"


class UserProfileUpdateInputSerializer(serializers.ModelSerializer):
    cloudflare_image_id = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = UserProfile
        fields = "__all__"
        extra_kwargs = {"user": {"read_only": True}, "avatar": {"read_only": True}}

    def update(self, instance, validated_data):
        cloudflare_id = validated_data.pop("cloudflare_image_id", None)
        if cloudflare_id:
            from django_cloudflareimages_toolkit.models import CloudflareImage

            image, _ = CloudflareImage.objects.get_or_create(cloudflare_id=cloudflare_id)
            instance.avatar = image

        return super().update(instance, validated_data)


class UserProfileOutputSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    avatar_url = serializers.SerializerMethodField()

    class Meta:
        model = UserProfile
        fields = "__all__"

    @extend_schema_field(serializers.URLField(allow_null=True))
    def get_avatar_url(self, obj) -> str | None:
        """Get user avatar URL"""
        # Safely try to return an avatar url if present
        avatar = getattr(obj, "avatar", None)
        if avatar:
            return getattr(avatar, "url", None)
        user_profile = getattr(obj, "user", None)
        if user_profile and getattr(user_profile, "profile", None):
            avatar = getattr(user_profile.profile, "avatar", None)
            if avatar:
                return getattr(avatar, "url", None)
        return None
