"""
Serializers for Settings Models
"""
from rest_framework import serializers
from .settings_models import SystemSettings, AccountSettings, UserSettings, ModuleSettings, AISettings
from .validators import validate_settings_schema


class SystemSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = SystemSettings
        fields = ['id', 'key', 'value', 'description', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']
    
    def validate_value(self, value):
        """Validate value against schema if schema exists"""
        if self.instance:
            validate_settings_schema(self.instance.key, value)
        return value


class AccountSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = AccountSettings
        fields = ['id', 'key', 'config', 'is_active', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at', 'account']
    
    def validate_config(self, value):
        """Validate config against schema if schema exists"""
        if self.instance:
            validate_settings_schema(self.instance.key, value)
        return value


class UserSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserSettings
        fields = ['id', 'key', 'value', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at', 'user', 'account']
    
    def validate_value(self, value):
        """Validate value against schema if schema exists"""
        if self.instance:
            validate_settings_schema(self.instance.key, value)
        return value


class ModuleSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModuleSettings
        fields = ['id', 'module_name', 'key', 'config', 'is_active', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at', 'account']
    
    def validate_config(self, value):
        """Validate config against schema if schema exists"""
        if self.instance:
            validate_settings_schema(self.instance.key, value)
        return value


class AISettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = AISettings
        fields = [
            'id', 'integration_type', 'config', 'model_preferences',
            'cost_limits', 'is_active', 'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at', 'account']

