package ru.forbion.f7cloud.feature.mail

import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns

internal object MailAttachmentIO {
    fun readUri(
        context: Context,
        uri: Uri,
        fallbackName: String = "attachment.bin",
    ): Triple<String, ByteArray, String> {
        val resolver = context.contentResolver
        var name = fallbackName
        resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (idx >= 0) {
                    name = cursor.getString(idx)?.takeIf { it.isNotBlank() } ?: name
                }
            }
        }
        val mime = resolver.getType(uri) ?: "application/octet-stream"
        val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
            ?: error("Не удалось прочитать файл")
        return Triple(name, bytes, mime)
    }
}
