package com.seyalix.hr.api

import android.content.Context
import android.content.Intent
import com.seyalix.hr.utils.PrefsManager
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ApiClient {

    // ── Change this to your server URL ────────────────────────
    private const val BASE_URL = "https://adrieltech.com/seyalix/api/v1/"

    private var prefs: PrefsManager? = null
    private var appContext: Context? = null

    fun init(ctx: Context) {
        appContext = ctx.applicationContext
        prefs = PrefsManager(ctx)
    }

    private val authInterceptor = Interceptor { chain ->
        val token = prefs?.getToken() ?: ""
        val req = if (token.isNotEmpty()) {
            chain.request().newBuilder()
                .addHeader("Authorization", "Bearer $token")
                .build()
        } else chain.request()

        val response = chain.proceed(req)

        // Auto-logout if token expired/invalid (401 Unauthorized)
        if (response.code == 401) {
            prefs?.logout()
            appContext?.let { ctx ->
                // Direct class reference instead of Class.forName(String) —
                // survives R8/ProGuard obfuscation in release builds without
                // needing a matching -keep rule (string-based reflection
                // silently breaks the moment the class gets renamed).
                val intent = Intent(ctx, com.seyalix.hr.ui.auth.LoginActivity::class.java).apply {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                }
                ctx.startActivity(intent)
            }
        }

        response
    }

    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    private val client = OkHttpClient.Builder()
        .addInterceptor(authInterceptor)
        .addInterceptor(loggingInterceptor)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()

    val apiService: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}
