from rest_framework import serializers
from .models import CostSheet, CostSheetMember, CostSheetTool


class CostSheetMemberSerializer(serializers.ModelSerializer):
    user_name = serializers.CharField(source='user.full_name', read_only=True)
    department = serializers.CharField(source='user.department', read_only=True)
    user_initials = serializers.CharField(source='user.initials', read_only=True)

    class Meta:
        model = CostSheetMember
        fields = [
            'id', 'user', 'user_name', 'user_initials', 'department',
            'project_role', 'hourly_rate', 'estimated_hours', 'total_cost'
        ]
        read_only_fields = ['id', 'total_cost']


class CostSheetToolSerializer(serializers.ModelSerializer):
    class Meta:
        model = CostSheetTool
        fields = ['id', 'name', 'purpose', 'cost']
        read_only_fields = ['id']


class CostSheetListSerializer(serializers.ModelSerializer):
    lead_title = serializers.CharField(source='lead.title', read_only=True)
    client_name = serializers.CharField(source='lead.client_name', read_only=True)
    created_by_name = serializers.CharField(source='created_by.full_name', read_only=True)

    class Meta:
        model = CostSheet
        fields = [
            'id', 'lead', 'lead_title', 'client_name', 'version', 'status',
            'total_cost', 'client_budget', 'budget_status',
            'created_by', 'created_by_name', 'created_at', 'updated_at'
        ]


class CostSheetDetailSerializer(serializers.ModelSerializer):
    lead_title = serializers.CharField(source='lead.title', read_only=True)
    client_name = serializers.CharField(source='lead.client_name', read_only=True)
    created_by_name = serializers.CharField(source='created_by.full_name', read_only=True)
    team_members = CostSheetMemberSerializer(many=True, read_only=True)
    tool_items = CostSheetToolSerializer(many=True, read_only=True)

    class Meta:
        model = CostSheet
        fields = [
            'id', 'lead', 'lead_title', 'client_name', 'version', 'status',
            'hr_cost', 'tools_cost',
            'overhead_type', 'overhead_value', 'overhead_cost',
            'contingency_percent', 'contingency_cost',
            'profit_percent', 'profit_amount',
            'subtotal', 'total_with_buffer', 'total_cost',
            'client_budget', 'budget_status', 'notes',
            'team_members', 'tool_items',
            'created_by', 'created_by_name', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'hr_cost', 'tools_cost', 'overhead_cost',
            'contingency_cost', 'profit_amount',
            'subtotal', 'total_with_buffer', 'total_cost',
            'client_budget', 'budget_status',
            'created_by', 'created_at', 'updated_at'
        ]
