package app.voltplan.cable.library

import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Query

const val POCKETBASE_BASE = "https://base.voltplan.app"

@Serializable
data class PbComponentsResponse(
    val page: Int = 1,
    val perPage: Int = 0,
    val totalPages: Int = 0,
    val items: List<PbComponentRecord> = emptyList(),
)

@Serializable
data class PbComponentRecord(
    val id: String,
    val collectionId: String = "",
    val name: String = "",
    val translations: JsonElement? = null,
    val icon: String? = null,
    @SerialName("voltage_in") val voltageIn: Double? = null,
    @SerialName("voltage_out") val voltageOut: Double? = null,
    val watt: Double? = null,
    @SerialName("duty_cycle") val dutyCycle: Double? = null,
    @SerialName("default_utilization_factor") val defaultUtilizationFactor: Double? = null,
)

@Serializable
data class PbAffiliateResponse(
    val page: Int = 1,
    val totalPages: Int = 0,
    val items: List<PbAffiliateRecord> = emptyList(),
)

@Serializable
data class PbAffiliateRecord(
    val id: String,
    val url: String = "",
    val component: String? = null,
    val country: String? = null,
)

interface PocketBaseApi {
    @GET("/api/collections/components/records")
    suspend fun components(
        @Query("filter") filter: String = "type='load'",
        @Query("sort") sort: String = "+name",
        @Query("fields") fields: String = "id,collectionId,name,translations,icon,voltage_in,voltage_out,watt,duty_cycle,default_utilization_factor",
        @Query("page") page: Int,
        @Query("perPage") perPage: Int = 200,
    ): PbComponentsResponse

    @GET("/api/collections/affiliate_links/records")
    suspend fun affiliateLinks(
        @Query("filter") filter: String,
        @Query("fields") fields: String = "id,url,component,country",
        @Query("page") page: Int,
        @Query("perPage") perPage: Int = 200,
    ): PbAffiliateResponse

    companion object {
        fun create(): PocketBaseApi {
            val json = Json { ignoreUnknownKeys = true; isLenient = true }
            val client = OkHttpClient.Builder().build()
            return Retrofit.Builder()
                .baseUrl(POCKETBASE_BASE)
                .client(client)
                .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
                .build()
                .create(PocketBaseApi::class.java)
        }
    }
}
