"""
Integrations serializers
"""
from rest_framework import serializers

from .models import EventMapping, InboundEvent, IntegrationConfig


class InboundEventSerializer(serializers.ModelSerializer):
    """Inbound event serializer"""
    
    class Meta:
        model = InboundEvent
        fields = [
            'id', 'source_system', 'event_code', 'encounter_id', 'patient_identifier',
            'payload_json', 'status', 'received_at', 'processed_at',
            'error', 'processing_attempts',
            'physician_license', 'department_code', 'metadata',
            'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'status', 'received_at', 'processed_at',
            'error', 'processing_attempts', 'metadata',
            'created_at', 'updated_at'
        ]


class InboundEventCreateSerializer(serializers.ModelSerializer):
    """
    Serializer for creating inbound events via API.
    
    External systems POST to /api/integrations/events/ with:
    {
        "source_system": "his",
        "event_code": "OPD_VISIT_COMPLETED",
        "encounter_id": "ENC123456",
        "patient_identifier": "MRN789",
        "payload_json": {
            "physician_license": "PHY001",
            "department_code": "DEPT_OPD",
            "timestamp": "2025-12-14T10:30:00Z",
            ...
        }
    }
    """
    
    class Meta:
        model = InboundEvent
        fields = [
            'source_system', 'event_code', 'encounter_id',
            'patient_identifier', 'payload_json'
        ]
    
    def create(self, validated_data):
        """
        Create event and extract context from payload.
        Event will be processed asynchronously by Celery task.
        """
        payload = validated_data.get('payload_json', {})
        
        # Extract physician and department from payload
        validated_data['physician_license'] = payload.get('physician_license', '')
        validated_data['department_code'] = payload.get('department_code', '')
        
        event = InboundEvent.objects.create(**validated_data)
        
        # Queue event for processing (will be implemented in tasks.py)
        # from apps.integrations.tasks import process_inbound_event
        # process_inbound_event.delay(event.id)
        
        return event


class InboundEventListSerializer(serializers.ModelSerializer):
    """Simplified inbound event serializer for list views"""
    
    class Meta:
        model = InboundEvent
        fields = [
            'id', 'source_system', 'event_code', 'encounter_id',
            'status', 'processing_attempts', 'received_at'
        ]


class EventMappingSerializer(serializers.ModelSerializer):
    """Event mapping serializer"""
    integration_name = serializers.CharField(source='integration_config.name', read_only=True)
    
    class Meta:
        model = EventMapping
        fields = [
            'id', 'integration_config', 'integration_name',
            'external_event_code', 'internal_event_code',
            'field_mappings', 'is_active',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class IntegrationConfigSerializer(serializers.ModelSerializer):
    """Integration configuration serializer"""
    event_mappings = EventMappingSerializer(many=True, read_only=True)
    
    class Meta:
        model = IntegrationConfig
        fields = [
            'id', 'name', 'source_system', 'description',
            'api_url', 'is_active', 'config_json',
            'event_mappings', 'last_sync_at',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'last_sync_at', 'created_at', 'updated_at']
        extra_kwargs = {
            'api_key': {'write_only': True}  # Don't expose API key in responses
        }
