package com.fabledsword.minstrel.admin.data

import com.fabledsword.minstrel.api.endpoints.AdminTagSourcesApi
import com.fabledsword.minstrel.api.endpoints.UpdateTagSourceBody
import com.fabledsword.minstrel.models.AdminTagSourceRef
import com.fabledsword.minstrel.models.TagSourceTestResult
import com.fabledsword.minstrel.models.wire.AdminTagSourceWire
import com.fabledsword.minstrel.models.wire.TestTagSourceWire
import retrofit2.Retrofit
import retrofit2.create
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Read-through accessor for the tag-enrichment provider settings (#1521).
 * No Room caching — admin settings are infrequent point-and-shoot edits;
 * mutations fire direct REST and the ViewModel reconciles on failure.
 * Exceptions propagate to the ViewModel (which maps them via ErrorCopy).
 */
@Singleton
class AdminTagSourcesRepository @Inject constructor(
    retrofit: Retrofit,
) {
    private val api: AdminTagSourcesApi = retrofit.create()

    suspend fun list(): List<AdminTagSourceRef> = api.list().providers.map { it.toDomain() }

    suspend fun setEnabled(id: String, enabled: Boolean): AdminTagSourceRef =
        api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()

    suspend fun setApiKey(id: String, apiKey: String): AdminTagSourceRef =
        api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain()

    suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult()
}

private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef = AdminTagSourceRef(
    id = id,
    displayName = displayName,
    requiresApiKey = requiresApiKey,
    supports = supports,
    enabled = enabled,
    apiKeySet = apiKeySet,
    testable = testable,
)

private fun TestTagSourceWire.toResult(): TagSourceTestResult =
    TagSourceTestResult(ok = ok, durationMs = durationMs, error = error)
