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

import com.github.nullptroma.wallenc.domain.vault.network.yandexdisk.YandexDiskApiFactory
import com.github.nullptroma.wallenc.domain.vault.network.yandexdisk.repository.YandexDiskRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

/**
 * Live-прогон Disk API. Пути только `app:/` — как в [YandexVault]; токен из Auth SDK
 * обычно имеет `cloud_api:disk.app_folder`, без полного доступа к `disk:/` (там 403).
 */
@RunWith(JUnit4::class)
class YandexDiskLiveIntegrationTest {

    private lateinit var repository: YandexDiskRepository
    private val testFolder = "app:/wallenc-integration-test"
    private val probeFileName = "wallenc-probe.txt"
    private val probePath = "$testFolder/$probeFileName"
    private val probePayload = "wallenc-integration-probe".encodeToByteArray()

    @Before
    fun setUp() {
        YandexTestCredentials.assumePresent()
        val token = YandexTestCredentials.oauthToken()!!
        repository = YandexDiskApiFactory.createRepositoryWithToken(token, Dispatchers.IO)
        runBlocking {
            runCatching { repository.createFolder(testFolder) }
            runCatching {
                repository.uploadBytes(probePath, probePayload, overwrite = true)
            }
        }
    }

    @After
    fun tearDown(): Unit = runBlocking {
        runCatching { repository.delete(probePath, permanently = true) }
    }

    @Test
    fun diskInfoReturnsQuota() = runBlocking {
        val info = repository.diskInfo()
        assertNotNull(info.totalSpace)
        assertTrue(info.totalSpace!! > 0)
    }

    @Test
    fun listTestFolderDoesNotThrow() = runBlocking {
        val result = repository.list(testFolder, limit = 10, offset = 0)
        assertNotNull(result)
    }

    @Test
    fun uploadAndDownloadRoundTrip() = runBlocking {
        val path = "$testFolder/roundtrip-${System.currentTimeMillis()}.bin"
        try {
            repository.uploadBytes(path, probePayload, overwrite = true)
            val downloaded = repository.openDownloadStream(path).use { it.readBytes() }
            assertTrue(downloaded.contentEquals(probePayload))
        } finally {
            runCatching { repository.delete(path, permanently = true) }
        }
    }
}
