package com.seven.ikar.kotlin.core.push

import android.content.Context
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

object AndroidFirebaseOptionsLoader {
    private var cached: AndroidFirebaseOptions? = null

    fun tryLoad(context: Context): AndroidFirebaseOptions? {
        cached?.let { return it }

        return runCatching {
            context.assets.open("firebase.android.json").bufferedReader().use { reader ->
                Json { ignoreUnknownKeys = true }
                    .decodeFromString(AndroidFirebaseOptions.serializer(), reader.readText())
            }
        }.getOrNull()?.takeIf {
            it.applicationId.isNotBlank() &&
                it.projectId.isNotBlank() &&
                it.apiKey.isNotBlank() &&
                it.senderId.isNotBlank()
        }?.also {
            cached = it
        }
    }
}

@Serializable
data class AndroidFirebaseOptions(
    val applicationId: String,
    val projectId: String,
    val apiKey: String,
    val senderId: String
)
