package pt.whatsms.gateway.modules.orchestrator

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import pt.whatsms.gateway.modules.events.EventBus
import pt.whatsms.gateway.modules.events.ExternalEvent
import pt.whatsms.gateway.modules.events.ExternalEventType
import pt.whatsms.gateway.modules.gateway.events.MessageEnqueuedEvent
import pt.whatsms.gateway.modules.gateway.events.SettingsUpdatedEvent
import pt.whatsms.gateway.modules.gateway.events.WebhooksUpdatedEvent
import pt.whatsms.gateway.modules.receiver.events.MessagesExportRequestedEvent

class EventsRouter(
    private val eventBus: EventBus
) {
    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    fun route(event: ExternalEvent) {
        scope.launch {
            when (event.type) {
                ExternalEventType.MessageEnqueued ->
                    eventBus.emit(
                        MessageEnqueuedEvent()
                    )

                ExternalEventType.WebhooksUpdated ->
                    eventBus.emit(
                        WebhooksUpdatedEvent()
                    )

                ExternalEventType.MessagesExportRequested ->
                    eventBus.emit(
                        MessagesExportRequestedEvent.withPayload(
                            requireNotNull(event.data)
                        )
                    )

                ExternalEventType.SettingsUpdated ->
                    eventBus.emit(
                        SettingsUpdatedEvent()
                    )
            }
        }
    }
}