from django.contrib.auth import get_user_model
from rest_framework import serializers

# Intentional cross-app import: users depends on photos for DB-backed avatar.
from apps.photos.models import Photo

User = get_user_model()


class UserProfileSerializer(serializers.ModelSerializer):
    # Write: accept a Photo PK; Read: return the serve URL
    avatar = serializers.PrimaryKeyRelatedField(
        required=False,
        allow_null=True,
        queryset=Photo.objects.all(),
    )
    avatar_url = serializers.SerializerMethodField()
    is_staff = serializers.BooleanField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'email', 'username', 'first_name', 'last_name',
                  'avatar', 'avatar_url', 'is_staff', 'language']
        read_only_fields = ['id', 'email', 'username', 'is_staff']

    def get_avatar_url(self, obj) -> str | None:
        if not obj.avatar_id:
            return None
        return f'/api/photos/{obj.avatar_id}/data/'


class AdminUserSerializer(serializers.ModelSerializer):
    """Flat serializer for the admin user-management panel."""

    class Meta:
        model = User
        fields = ['id', 'email', 'username', 'first_name', 'last_name',
                  'is_active', 'is_staff', 'date_joined']
        read_only_fields = ['id', 'email', 'username', 'date_joined']


class AdminCreateUserSerializer(serializers.ModelSerializer):
    """Serializer used by admins to create a new user account."""
    password = serializers.CharField(write_only=True, min_length=8)

    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'first_name', 'last_name', 'is_staff']

    def create(self, validated_data):
        password = validated_data.pop('password')
        return User.objects.create_user(password=password, **validated_data)
