SeasonRecords.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/SeasonRecords.kt
1package eu.friedcutlet.yokan.data23import eu.friedcutlet.yokan.database.DbFetchType4import eu.friedcutlet.yokan.database.DbManga5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.services.extensions.RemoteManga78/**9 * Writes the Animetail season records of a Seasons-type [parent]; call inside `database.batch`.10 * Each season is its own title linked by [DbManga.parentId]; favorites, covers and progress stay.11 * Seasons absent from a response are kept, so a partial source reply never drops progress.12 */13internal fun YokanDatabase.upsertSeasonRecords(parent: DbManga, seasons: List<RemoteManga>, now: Long): List<DbManga> {14 val byLink = mangas(parent.itemType)15 .filter { it.id != parent.id && it.sourceId == parent.sourceId && it.source == parent.source }16 .groupBy { it.link }17 return seasons.map { season ->18 val candidates = byLink[season.url].orEmpty()19 // A previously browsed, non-library title with the season's URL becomes the season record.20 val existing = candidates.firstOrNull { it.parentId == parent.id }21 ?: candidates.firstOrNull { it.parentId == null && !it.favorite }22 val next = (existing ?: DbManga()).copy(23 name = season.title,24 link = season.url,25 imageUrl = season.thumbnailUrl ?: existing?.imageUrl,26 description = season.description ?: existing?.description,27 itemType = parent.itemType,28 source = parent.source,29 sourceId = parent.sourceId,30 lang = parent.lang,31 isLocalArchive = parent.isLocalArchive,32 parentId = parent.id,33 seasonNumber = season.seasonNumber ?: existing?.seasonNumber,34 fetchType = if (season.fetchesSeasons) DbFetchType.Seasons else existing?.fetchType ?: DbFetchType.Episodes,35 favorite = existing?.favorite ?: false,36 dateAdded = existing?.dateAdded ?: now,37 lastUpdate = existing?.lastUpdate ?: now,38 )39 if (existing != null && next == existing) existing else upsertManga(next.copy(updatedAt = now))40 }41}42