from rest_framework import serializers

from apps.standards.models import (
    StandardSource,
    StandardCategory,
    Standard,
    StandardCompliance,
    StandardAttachment
)


class StandardSourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = StandardSource
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class StandardCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = StandardCategory
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class StandardSerializer(serializers.ModelSerializer):
    source_name = serializers.CharField(source='source.name', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    department_name = serializers.CharField(source='department.name', read_only=True)

    class Meta:
        model = Standard
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class StandardComplianceSerializer(serializers.ModelSerializer):
    department_name = serializers.CharField(source='department.name', read_only=True)
    standard_code = serializers.CharField(source='standard.code', read_only=True)
    standard_title = serializers.CharField(source='standard.title', read_only=True)
    assessor_name = serializers.CharField(source='assessor.get_full_name', read_only=True)
    attachment_count = serializers.SerializerMethodField()

    class Meta:
        model = StandardCompliance
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']

    def get_attachment_count(self, obj):
        return obj.attachments.count()


class StandardAttachmentSerializer(serializers.ModelSerializer):
    uploaded_by_name = serializers.CharField(source='uploaded_by.get_full_name', read_only=True)
    standard_code = serializers.CharField(source='compliance.standard.code', read_only=True)
    department_name = serializers.CharField(source='compliance.department.name', read_only=True)

    class Meta:
        model = StandardAttachment
        fields = '__all__'
        read_only_fields = ['id', 'uploaded_at', 'created_at', 'updated_at']
