package dev.inmo.postssystem.features.publication.server

import dev.inmo.micro_utils.coroutines.asyncSafelyWithoutExceptions
import dev.inmo.postssystem.features.content.server.storage.ServerReadContentStorage
import dev.inmo.postssystem.features.posts.common.PostId
import dev.inmo.postssystem.features.posts.server.ServerReadPostsStorage
import kotlinx.coroutines.*

class PublicationManager (
    private val targets: List<PublicationTarget>,
    private val postsRepo: ServerReadPostsStorage,
    private val contentRepo: ServerReadContentStorage,
    private val scope: CoroutineScope
) {
    suspend fun publish(
        postId: PostId
    ) {
        val post = postsRepo.getById(postId) ?: return
        val content = post.content.map {
            scope.async {
                contentRepo.getById(it)
            }
        }.awaitAll().filterNotNull()

        val publicationPost = PublicationPost(post, content)

        targets.map {
            scope.asyncSafelyWithoutExceptions {
                it.publish(publicationPost)
            }
        }.awaitAll()
    }
}
