package com.github.nullptroma.wallenc.app.integration.yandex

import android.util.Log
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.nullptroma.wallenc.infrastructure.android.db.app.AppDb
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith

/**
 * Ручной helper: после входа в Yandex через приложение печатает в Logcat маскированный
 * токен и подсказку для local.properties. Запускать вручную из Android Studio.
 */
@RunWith(AndroidJUnit4::class)
@Ignore("Manual: export Yandex credentials to local.properties")
class ExportYandexTestCredentialsTest {

    @Test
    fun printFirstAccountCredentialsToLogcat() {
        val context = ApplicationProvider.getApplicationContext<android.content.Context>()
        val db = Room.databaseBuilder(context, AppDb::class.java, "wallenc.db")
            .build()
        try {
            val row = runBlocking {
                db.yandexAccountDao.observeAll().first().firstOrNull()
            }
            if (row == null) {
                Log.i(TAG, "No Yandex accounts in DB. Link a vault in the app first.")
                return
            }
            Log.i(TAG, "Add to local.properties:")
            Log.i(TAG, "yandex.test.oauth.token=<copy full token from app debug storage if needed>")
            Log.i(TAG, "yandex.test.oauth.token.prefix=${maskToken(row.oauthToken)}")
            Log.i(TAG, "yandex.test.user.id=${row.yandexUserId}")
            Log.i(TAG, "yandex.test.vault.uuid=${row.vaultUuid}")
        } finally {
            db.close()
        }
    }

    private fun maskToken(token: String): String {
        if (token.length <= 8) return "***"
        return token.take(4) + "…" + token.takeLast(4)
    }

    companion object {
        private const val TAG = "WallencYandexExport"
    }
}
