from rest_framework import serializers
from django.contrib.auth import authenticate
from .models import User, UserRole, LoginAttempt


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

    def validate_role(self, value):
        valid_roles = [role.value for role in UserRole]
        if value not in valid_roles:
            raise serializers.ValidationError("Invalid role")
        return value

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


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        user = authenticate(username=data['username'], password=data['password'])
        if not user:
            raise serializers.ValidationError("Invalid username or password")
        data['user'] = user
        return data



class LoginAttemptSerializer(serializers.ModelSerializer):
    class Meta:
        model = LoginAttempt
        fields = [
            'id', 'username', 'attempts', 'last_attempt', 'blocked_until'
        ]