package eu.kanade.domain.manga.interactor

import eu.kanade.domain.manga.model.Manga
import eu.kanade.domain.manga.repository.MangaRepository

class NetworkToLocalManga(
    private val mangaRepository: MangaRepository,
) {

    suspend fun await(manga: Manga, sourceId: Long): Manga {
        val localManga = getManga(manga.url, sourceId)
        return when {
            localManga == null -> {
                val id = insertManga(manga, sourceId)
                manga.copy(id = id!!)
            }
            !localManga.favorite -> {
                // if the manga isn't a favorite, set its display title from source
                // if it later becomes a favorite, updated title will go to db
                localManga.copy(/* SY --> */ogTitle/* SY <-- */ = manga.title)
            }
            else -> {
                localManga
            }
        }
    }

    private suspend fun getManga(url: String, sourceId: Long): Manga? {
        return mangaRepository.getMangaByUrlAndSourceId(url, sourceId)
    }

    private suspend fun insertManga(manga: Manga, sourceId: Long): Long? {
        return mangaRepository.insert(manga.copy(source = sourceId))
    }
}
