package com.pixelized.biblib.network.factory

import com.pixelized.biblib.model.book.Genre
import com.pixelized.biblib.network.data.response.GenreListResponse
import com.pixelized.biblib.utils.exception.missingField

class GenreFactory {
    fun fromListResponseToGenreHash(
        response: GenreListResponse,
    ): Map<Int, List<Genre>> {
        fun error(name: String) = missingField("#fromListResponseToGenreHash()", name, response)

        val hash = mutableMapOf<Int, MutableList<Genre>>()

        response.genres?.forEach { data ->
            val genre = Genre(
                id = data.tag_id ?: throw error("id"),
                name = data.tag_name ?: throw error("name"),
            )
            data.books?.forEach { book ->
                book.book_id?.let { id ->
                    hash.getOrPut(id) { mutableListOf() }.add(genre)
                }
            }
        }

        return hash
    }
}