from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()

class UserProfileSerializer(serializers.ModelSerializer):
    """Сериализатор для профиля пользователя"""
    avatar_url = serializers.SerializerMethodField()
    cover_url = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 
                 'full_name', 'bio', 'avatar', 'cover', 'avatar_url', 'cover_url']
        read_only_fields = ['id', 'username']
    
    def get_avatar_url(self, obj):
        if obj.avatar:
            request = self.context.get('request')
            if request:
                # Заменяем внутренний Docker URL на localhost для клиента
                absolute_uri = request.build_absolute_uri(obj.avatar.url)
                return absolute_uri.replace('http://web:8000', 'http://localhost:8000')
        return None
    
    def get_cover_url(self, obj):
        if obj.cover:
            request = self.context.get('request')
            if request:
                # Заменяем внутренний Docker URL на localhost для клиента
                absolute_uri = request.build_absolute_uri(obj.cover.url)
                return absolute_uri.replace('http://web:8000', 'http://localhost:8000')
        return None

@api_view(['GET', 'PUT', 'PATCH'])
@permission_classes([IsAuthenticated])
def user_profile(request):
    """
    Получение и обновление профиля пользователя
    """
    user = request.user
    
    if request.method == 'GET':
        serializer = UserProfileSerializer(user, context={'request': request})
        return Response(serializer.data)
    
    elif request.method in ['PUT', 'PATCH']:
        partial = request.method == 'PATCH'
        serializer = UserProfileSerializer(
            user, 
            data=request.data, 
            partial=partial,
            context={'request': request}
        )
        
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
