from rest_framework import serializers
from crm.models.office import Office

class OfficeSerializer(serializers.ModelSerializer):
    location_display = serializers.CharField(source='get_location_code_display', read_only=True)
    
    class Meta:
        model = Office
        fields = [
            'id', 'name', 'location_code', 'location_display', 
            'address', 'phone', 'email', 'website', 'gstin',
            'is_active', 'is_default', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def validate(self, data):
        # Ensure only one default office exists
        if data.get('is_default', False):
            existing_default = Office.objects.filter(is_default=True).exclude(id=self.instance.id if self.instance else None)
            if existing_default.exists():
                raise serializers.ValidationError("Only one office can be set as default.")
        return data
