package com.pixelized.biblib.network.factory

import com.pixelized.biblib.model.book.Series
import com.pixelized.biblib.network.data.response.SeriesListResponse
import com.pixelized.biblib.utils.exception.missingField

typealias SeriesHash = Map<Int, Pair<Int, Series>>

class SeriesFactory {
    fun fromListResponseToSeriesHash(
        response: SeriesListResponse,
    ): SeriesHash {
        fun error(name: String) = missingField("#fromListResponseToSeriesHash()", name, response)

        // BOOK_ID, BOOK_SERIES_INDEX, SERIES
        val hash = mutableMapOf<Int, Pair<Int, Series>>()

        response.series?.forEach { data ->
            // build the Series items
            val series = Series(
                id = data.series_id ?: throw error("id"),
                name = data.series_name ?: throw error("name"),
                sort = data.series_sort ?: throw error("sort"),
            )
            // link that item to the book id.
            data.books?.forEachIndexed { index, book ->
                book.book_id?.let { id -> hash[id] = (index + 1) to series }
            }
        }

        return hash
    }
}