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


class DeleteAccountSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate(self, data):
        phone = data.get("phone")
        password = data.get("password")
        user = authenticate(phone=phone, password=password)

        if user is None:
            raise serializers.ValidationError(
                "Telefon raqam yoki parol noto'g'ri."
            )

        if user != self.context["request"].user:
            raise serializers.ValidationError("Telefon raqam noto'g'ri.")

        return data

    def delete(self):
        user = self.context["request"].user
        user.delete()
        return user
