from .models import *
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    otp = serializers.CharField(required=False)
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        del self.fields['password']


class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'profile_photo', 'phone', 'gender', 'birth_date']
        read_only_fields = ("phone",)


class UserAddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAddressModel
        fields = ['id', 'name', 'address', 'postal_code', 'phone', 'city', 'province', 'for_me', 'is_main']
        read_only_fields = ('id',)
    def validate(self, data):
        user = self.context['request'].user
        if not user.is_authenticated:
            raise serializers.ValidationError("You must be logged in to perform this action.")
        return data


class PushSubscriptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = PushSubscription
        fields = ('endpoint', 'keys')


class NewsSerializer(serializers.ModelSerializer):
    notif_type = serializers.SerializerMethodField()

    class Meta:
        model = NewsModel
        fields = ['title', 'content', 'created_at', 'notif_type']

    def get_notif_type(self, obj):
        return 'NEWS'

class UserNotifSerializer(serializers.ModelSerializer):
    notif_type = serializers.SerializerMethodField()

    class Meta:
        model = UserNotificationModel
        fields = ['title', 'content', 'created_at', 'notif_type', 'is_read']

    def get_notif_type(self, obj):
        return 'USER_NOTIF'
    

class UnifiedNotifSerializer(serializers.Serializer):
    def to_representation(self, instance):
        if isinstance(instance, NewsModel):
            return NewsSerializer(instance).data
        elif isinstance(instance, UserNotificationModel):
            return UserNotifSerializer(instance).data
