# api/serializers.py
from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import Link, LinkGroup
from django.conf import settings
from .models import Link, LinkGroup
User = get_user_model()

class RegisterSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password', 'password2']
        extra_kwargs = {'password': {'write_only': True}}

    def validate(self, attrs):
        if attrs['password'] != attrs.pop('password2'):
            raise serializers.ValidationError("Пароли не совпадают")
        return attrs

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)




# сериализатор для ссылок
class UserSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'full_name', 'bio', 'avatar', 'avatar_url', 'last_login', 'date_joined']
        read_only_fields = ['avatar_url']

    def get_avatar_url(self, obj):
        """Возвращает полный URL аватара"""
        if obj.avatar:
            request = self.context.get('request')
            if request:
                absolute_uri = request.build_absolute_uri(obj.avatar.url)
                # Заменяем различные варианты внутренних Docker URL
                absolute_uri = absolute_uri.replace('http://web:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://links-web-1:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://backend:8000', 'http://localhost:8000')
                return absolute_uri
            return f'http://localhost:8000{obj.avatar.url}'
        return None


class LinkGroupSerializer(serializers.ModelSerializer):
    icon = serializers.ImageField(required=False, allow_null=True)
    background_image = serializers.ImageField(required=False, allow_null=True)
    icon_url = serializers.SerializerMethodField()
    background_image_url = serializers.SerializerMethodField()
    
    class Meta:
        model = LinkGroup
        fields = [
            'id', 'name', 'description', 'icon', 'icon_url', 'order', 
            'is_public', 'is_favorite', 'created_at', 'updated_at',
            # Новые поля кастомизации
            'header_color', 'background_image', 'background_image_url',
            'is_expanded', 'display_style'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'icon_url', 'background_image_url']

    def get_icon_url(self, obj):
        """Возвращает полный URL иконки"""
        if obj.icon:
            request = self.context.get('request')
            if request:
                absolute_uri = request.build_absolute_uri(obj.icon.url)
                # Заменяем различные варианты внутренних Docker URL
                absolute_uri = absolute_uri.replace('http://web:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://links-web-1:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://backend:8000', 'http://localhost:8000')
                return absolute_uri
            return f'http://localhost:8000{obj.icon.url}'
        return None

    def get_background_image_url(self, obj):
        """Возвращает полный URL фонового изображения"""
        if obj.background_image:
            request = self.context.get('request')
            if request:
                absolute_uri = request.build_absolute_uri(obj.background_image.url)
                # Заменяем различные варианты внутренних Docker URL
                absolute_uri = absolute_uri.replace('http://web:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://links-web-1:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://backend:8000', 'http://localhost:8000')
                return absolute_uri
            return f'http://localhost:8000{obj.background_image.url}'
        return None

    def validate_header_color(self, value):
        """Валидация цвета заголовка"""
        if not value.startswith('#') or len(value) != 7:
            raise serializers.ValidationError('Цвет должен быть в формате #RRGGBB')
        try:
            int(value[1:], 16)
        except ValueError:
            raise serializers.ValidationError('Некорректный hex цвет')
        return value

    def validate_display_style(self, value):
        """Валидация стиля отображения"""
        valid_styles = ['list', 'grid', 'cards', 'compact', 'sidebar', 'masonry', 'timeline', 'magazine']
        if value not in valid_styles:
            raise serializers.ValidationError(f'Стиль должен быть одним из: {", ".join(valid_styles)}')
        return value


class LinkSerializer(serializers.ModelSerializer):
    icon = serializers.ImageField(required=False, allow_null=True)
    icon_url = serializers.SerializerMethodField()
    
    class Meta:
        model = Link
        fields = ['id', 'title', 'url', 'icon', 'icon_url', 'group', 'order']
        read_only_fields = ['id', 'icon_url']
    
    def get_icon_url(self, obj):
        """Возвращает полный URL иконки ссылки"""
        if obj.icon:
            request = self.context.get('request')
            if request:
                absolute_uri = request.build_absolute_uri(obj.icon.url)
                # Заменяем различные варианты внутренних Docker URL
                absolute_uri = absolute_uri.replace('http://web:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://links-web-1:8000', 'http://localhost:8000')
                absolute_uri = absolute_uri.replace('http://backend:8000', 'http://localhost:8000')
                return absolute_uri
            return f'http://localhost:8000{obj.icon.url}'
        return None