package id.iiyh.inatrading.core.data.remote.interceptor

import id.iiyh.inatrading.core.data.local.SessionManager
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Response
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
import javax.inject.Inject

class HeaderInterceptor @Inject constructor(
    private val sessionManager: SessionManager,
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val token = runBlocking { sessionManager.token.firstOrNull() }
        val requestTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
        val refNo = "REF${System.currentTimeMillis()}${UUID.randomUUID().toString().replace("-", "").take(6).uppercase()}"

        val original = chain.request()
        val builder = original.newBuilder()
            .header("Request-Time", requestTime)
            .header("Channel-Id", "WEB")
            .header("Reference-Number", refNo)

        // Add Bearer token only if not already overridden (e.g. login uses Basic Auth via @Header)
        if (original.header("Authorization") == null && !token.isNullOrEmpty()) {
            builder.header("Authorization", "Bearer $token")
        }

        return chain.proceed(builder.build())
    }
}
