/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.core.auth.sso

import android.content.Context
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

/**
 * [PendingSsoStore] backed by Jetpack Security's [EncryptedSharedPreferences]
 * (Tink/AES-256-GCM), so the PKCE verifier is encrypted at rest for the brief
 * window a flow is in progress. Separate prefs file from the session token store —
 * this holds only the transient SSO handshake, cleared as soon as the callback is
 * consumed. Lazy, so a device that never signs in via SSO pays no keystore cost.
 */
@Singleton
class EncryptedPendingSsoStore @Inject constructor(
    @param:ApplicationContext private val context: Context,
) : PendingSsoStore {

    private val prefs: SharedPreferences by lazy {
        val masterKey = MasterKey.Builder(context)
            .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
            .build()
        EncryptedSharedPreferences.create(
            context,
            PREFS_NAME,
            masterKey,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
        )
    }

    override fun save(state: String, verifier: String) {
        prefs.edit()
            .putString(KEY_STATE, state)
            .putString(KEY_VERIFIER, verifier)
            .apply()
    }

    override fun load(): PendingSso? {
        val state = prefs.getString(KEY_STATE, null) ?: return null
        val verifier = prefs.getString(KEY_VERIFIER, null) ?: return null
        return PendingSso(state = state, verifier = verifier)
    }

    override fun clear() {
        prefs.edit().clear().apply()
    }

    private companion object {
        const val PREFS_NAME = "runic_sso_pending"
        const val KEY_STATE = "state"
        const val KEY_VERIFIER = "verifier"
    }
}
