from rest_framework import serializers
from django.contrib.auth import get_user_model, authenticate
from django.utils import timezone

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        # DROŠĪBA (HIGH-05): telegram_link_code noņemts no vispārējā serializatora
        fields = ['id', 'email', 'full_name', 'role', 'is_active', 'is_staff']

class RegistrationSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    terms_accepted = serializers.BooleanField(required=True)
    
    class Meta:
        model = User
        fields = ['email', 'password', 'full_name', 'terms_accepted']

    def validate_terms_accepted(self, value):
        if not value:
            raise serializers.ValidationError("Jums jāpiekrīt lietošanas noteikumiem.")
        return value

    def create(self, validated_data):
        terms_accepted = validated_data.pop('terms_accepted', False)
        user = User.objects.create_user(
            email=validated_data['email'],
            password=validated_data['password'],
            full_name=validated_data.get('full_name', '')
        )
        user.is_active = False  # Lietotājs neaktīvs līdz e-pasta apstiprināšanai
        user.terms_accepted = terms_accepted
        if terms_accepted:
            user.accepted_at = timezone.now()
        user.save()
        return user

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

class VerifyOTPSerializer(serializers.Serializer):
    email = serializers.EmailField()
    otp = serializers.CharField(max_length=6)