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


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            "id", "email", "username", "role",
            "bio", "phone", "profile_image",
            "neighborhood", "ward",
            "followers_count", "following_count",
            "is_online", "last_seen", "date_joined",
            "is_verified", "verification_status",
            "is_staff",
        ]
        read_only_fields = (
            "id", "role", "followers_count", "following_count",
            "date_joined", "last_seen", "is_online"
        )


class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model  = User
        fields = ["email", "username", "password", "neighborhood", "ward"]

    def create(self, validated_data):
        if User.objects.filter(email=validated_data["email"]).exists():
            raise serializers.ValidationError({"email": "This email is already registered."})
        user = User.objects.create_user(
            email=validated_data["email"],
            username=validated_data["username"],
            password=validated_data["password"],
            role="resident",
            neighborhood=validated_data.get("neighborhood"),
            ward=validated_data.get("ward"),
        )
        return user


class LoginSerializer(serializers.Serializer):
    email    = serializers.EmailField()
    password = serializers.CharField(write_only=True)

    def validate(self, data):
        email    = data.get("email", "").strip()
        password = data.get("password", "")
        try:
            user_obj = User.objects.get(email=email)
        except User.DoesNotExist:
            raise serializers.ValidationError({"error": "Invalid login credentials."})

        # Check password first regardless of is_active
        user = authenticate(email=email, password=password)
        if not user and not user_obj.check_password(password):
            raise serializers.ValidationError({"error": "Invalid login credentials."})

        # Use user_obj directly if authenticate failed due to is_active=False
        if not user:
            user = user_obj

        data["user"] = user
        return data


class UpdateProfileSerializer(serializers.ModelSerializer):
    username      = serializers.CharField(required=False)
    bio           = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    phone         = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    neighborhood  = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    ward          = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    profile_image = serializers.ImageField(required=False, allow_null=True)

    class Meta:
        model  = User
        fields = ["username", "bio", "phone", "neighborhood", "ward", "profile_image"]
