from rest_framework import serializers
from course.models import Question, Exam, ExamAnswer, ExamResult, Certificate
from users.models import User

class QuestionSerializer(serializers.ModelSerializer):
    """Serializer for trainers to manage questions"""
    class Meta:
        model = Question
        fields = '__all__'

class QuestionStudentSerializer(serializers.ModelSerializer):
    """Serializer for students (without correct answer)"""
    class Meta:
        model = Question
        fields = ['id', 'question_text', 'option_a', 'option_b', 'option_c', 'option_d']

class ExamAnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = ExamAnswer
        fields = ['question', 'selected_answer']

class ExamSerializer(serializers.ModelSerializer):
    answers = ExamAnswerSerializer(many=True, write_only=True)
    
    class Meta:
        model = Exam
        fields = ['id', 'started_at', 'expires_at', 'score', 'is_passed', 'answers']
        read_only_fields = ['id', 'started_at', 'expires_at', 'score', 'is_passed']

class ExamResultSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='exam.enrollment.student.profile.name', read_only=True)
    course_name = serializers.CharField(source='exam.enrollment.course.name', read_only=True)
    
    class Meta:
        model = ExamResult
        fields = ['id', 'student_name', 'course_name', 'total_questions', 'correct_answers', 'score_percentage', 'rank', 'created_at']

class CertificateSearchSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='student.profile.name', read_only=True)
    student_email = serializers.CharField(source='student.profile.user.email', read_only=True)
    course_name = serializers.CharField(source='course.name', read_only=True)
    
    class Meta:
        model = Certificate
        fields = ['certificate_number', 'certificate_date', 'exam_score', 'certificate_url', 'student_name', 'student_email', 'course_name']