from rest_framework import serializers
from social_django.models import UserSocialAuth

from account.models import User


class UserSocialAuthSerializer(serializers.Serializer):
    account_id = serializers.IntegerField()
    provider = serializers.CharField()
    uid = serializers.CharField()

    def validate(self, data):
        data.update({
            'user': self.get_account(data),
        })
        data.pop('account_id')
        return data

    def create(self, validated_data):
        try:
            return UserSocialAuth.objects.create(**validated_data)
        except Exception as e:
            raise ValueError(f"Error creating UserSocialAuth with {validated_data}: {e}")

    @staticmethod
    def get_account(data):
        user = User.objects.filter(old_id=data['account_id']).first()
        if not user:
            raise ValueError(f"User account not found with old_id {data['account_id']}")
        return user
