package com.amz.genie.helpers

import android.content.Context
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

object AttachmentDownloader {

    fun downloadToCache(
        ctx: Context,
        url: String,
        fileName: String,
        token: String
    ): File {
        val safeName = fileName.ifBlank { "attachment_${System.currentTimeMillis()}" }
        val outFile = File(ctx.cacheDir, safeName)

        val client = OkHttpClient.Builder().build()

        val req = Request.Builder()
            .url(url)
            .addHeader("Authorization", token)
            .build()

        client.newCall(req).execute().use { resp ->
            if (!resp.isSuccessful) {
                throw RuntimeException("Download gagal: ${resp.code} ${resp.message}")
            }
            val body = resp.body ?: throw RuntimeException("Body kosong")
            outFile.outputStream().use { os ->
                body.byteStream().use { input ->
                    input.copyTo(os)
                }
            }
        }

        return outFile
    }
}