from rest_framework import serializers
from .models import Task, TaskComment, TimeLog

class TaskCommentSerializer(serializers.ModelSerializer):
    author_name = serializers.CharField(source='author.full_name', read_only=True)
    author_initials = serializers.SerializerMethodField()

    class Meta:
        model = TaskComment
        fields = ['id', 'author', 'author_name', 'author_initials', 'content', 'created_at']
        read_only_fields = ['author']

    def get_author_initials(self, obj):
        if obj.author and obj.author.full_name:
            return ''.join(n[0] for n in obj.author.full_name.split()[:2]).upper()
        return '?'


class TimeLogSerializer(serializers.ModelSerializer):
    user_name = serializers.CharField(source='user.full_name', read_only=True)
    task_title = serializers.CharField(source='task.title', read_only=True)

    class Meta:
        model = TimeLog
        fields = ['id', 'task', 'task_title', 'user', 'user_name', 'hours', 'date', 'note', 'created_at']
        read_only_fields = ['user']


class TaskSerializer(serializers.ModelSerializer):
    project_name = serializers.CharField(source='project.name', read_only=True)
    assignee_name = serializers.CharField(source='assigned_to.full_name', read_only=True)
    assignee_initials = serializers.SerializerMethodField()
    comments = TaskCommentSerializer(many=True, read_only=True)
    time_logs = TimeLogSerializer(many=True, read_only=True)
    logged_hours = serializers.SerializerMethodField()
    is_overdue = serializers.BooleanField(read_only=True)

    class Meta:
        model = Task
        fields = [
            'id', 'project', 'project_name', 'title', 'description', 
            'assigned_to', 'assignee_name', 'assignee_initials', 
            'status', 'priority', 'category', 'due_date', 
            'estimated_hours', 'logged_hours', 'blocked_by', 'created_by', 
            'created_at', 'updated_at', 'time_logs', 'comments', 'is_overdue'
        ]
        read_only_fields = ['created_by']

    def get_logged_hours(self, obj):
        return sum(log.hours for log in obj.time_logs.all())

    def get_assignee_initials(self, obj):
        if obj.assigned_to and obj.assigned_to.full_name:
            return ''.join(n[0] for n in obj.assigned_to.full_name.split()[:2]).upper()
        return '?'
