from rest_framework import serializers
from .models import ApprovalFlow, ApprovalAction


class ApprovalActionSerializer(serializers.ModelSerializer):
    actor_name = serializers.CharField(source='actor.full_name', read_only=True)
    actor_role = serializers.SerializerMethodField()

    def get_actor_role(self, obj):
        return obj.actor.roles.first().name if obj.actor.roles.exists() else 'Member'
    actor_initials = serializers.CharField(source='actor.initials', read_only=True)

    class Meta:
        model = ApprovalAction
        fields = [
            'id', 'stage', 'actor', 'actor_name', 'actor_role',
            'actor_initials', 'action', 'comment', 'timestamp'
        ]
        read_only_fields = ['id', 'stage', 'actor', 'timestamp']


class ApprovalFlowSerializer(serializers.ModelSerializer):
    actions = ApprovalActionSerializer(many=True, read_only=True)
    submitted_by_name = serializers.CharField(source='submitted_by.full_name', read_only=True)
    lead_title = serializers.CharField(source='lead.title', read_only=True)
    client_name = serializers.CharField(source='lead.client_name', read_only=True)
    cost_sheet_total = serializers.DecimalField(
        source='cost_sheet.total_cost', max_digits=14, decimal_places=2, read_only=True
    )
    client_budget = serializers.DecimalField(
        source='cost_sheet.client_budget', max_digits=14, decimal_places=2, read_only=True
    )

    class Meta:
        model = ApprovalFlow
        fields = [
            'id', 'cost_sheet', 'lead', 'lead_title', 'client_name',
            'current_stage', 'overall_status',
            'cost_sheet_total', 'client_budget',
            'submitted_by', 'submitted_by_name',
            'submitted_at', 'completed_at',
            'actions'
        ]
        read_only_fields = ['id', 'submitted_at', 'completed_at']
