package app.voltplan.cable.library

/** Fetches and assembles the component library from PocketBase. Mirrors `ComponentLibraryViewModel` data flow. */
class ComponentLibraryRepository(private val api: PocketBaseApi = PocketBaseApi.create()) {

    suspend fun fetchAll(): List<ComponentLibraryItem> {
        val records = fetchComponents()
        val affiliateByComponent = fetchAffiliateLinks(records.map { it.id })
        return records.map { record ->
            ComponentLibraryItem.from(record, affiliateByComponent[record.id].orEmpty())
        }
    }

    private suspend fun fetchComponents(): List<PbComponentRecord> {
        val all = mutableListOf<PbComponentRecord>()
        var page = 1
        val perPage = 200
        while (true) {
            val response = api.components(page = page, perPage = perPage)
            all += response.items
            val done = (response.totalPages in 1..page) || response.items.size < perPage
            if (done) break
            page++
        }
        return all
    }

    private suspend fun fetchAffiliateLinks(componentIds: List<String>): Map<String, List<AffiliateLink>> {
        if (componentIds.isEmpty()) return emptyMap()
        val result = HashMap<String, MutableList<AffiliateLink>>()
        componentIds.chunked(15).forEach { chunk ->
            val filter = chunk.joinToString(" || ") { "component='${it.replace("'", "\\'")}'" }.let { "($it)" }
            var page = 1
            val perPage = 200
            while (true) {
                val response = api.affiliateLinks(filter = filter, page = page, perPage = perPage)
                response.items.forEach { record ->
                    val component = record.component ?: return@forEach
                    val country = record.country?.trim()?.takeUnless { it.isEmpty() }?.uppercase()
                    result.getOrPut(component) { mutableListOf() }
                        .add(AffiliateLink(record.id, record.url, country))
                }
                val done = (response.totalPages in 1..page) || response.items.size < perPage
                if (done) break
                page++
            }
        }
        // Stable order: by country then url.
        return result.mapValues { (_, links) ->
            links.sortedWith(compareBy({ it.country ?: "" }, { it.url }))
        }
    }
}
