package com.amz.genie.services

import android.app.Application
import android.content.pm.ApplicationInfo
import android.util.Log
import androidx.appcompat.app.AppCompatDelegate
import com.amz.genie.helpers.Preferences
import com.google.firebase.FirebaseApp
import com.google.firebase.messaging.FirebaseMessaging
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class APIMain: Application() {
    companion object {
        lateinit var instance: APIMain
            private set

        fun require(): APIMain {
            check(::instance.isInitialized) {
                "APIMain belum diinisialisasi. Pastikan android:name='.services.APIMain' sudah ada " +
                        "di AndroidManifest dan jangan panggil APIMain() secara langsung."
            }
            return instance
        }
    }

    lateinit var accountServices: AuthServices
    lateinit var generalServices: GeneralServices
    lateinit var reaksiServices: ReaksiServices
    lateinit var selectionServices: SelectionServices
    lateinit var actionServices: ActionServices

    override fun onCreate() {
        super.onCreate()

        // Paksa aplikasi selalu LIGHT (disable dark mode)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

        instance = this

        val firebaseApp = runCatching { FirebaseApp.initializeApp(this) }.getOrNull()
        if (firebaseApp == null) {
            Log.e("FirebaseInit", "FirebaseApp.initializeApp() returned NULL. App lanjut tanpa Firebase.")
        } else {
            runCatching {
                FirebaseMessaging.getInstance().isAutoInitEnabled = true
                Log.d("FirebaseInit", "Firebase ready, FCM autoInit enabled")
            }.onFailure {
                Log.e("FirebaseInit", "FCM init failed: ${it.message}", it)
            }
        }

        Log.d("APIMain", "onCreate() called, initializing Retrofit...")

        val tokenRepo = TokenRepository(this)

        val isDebug = (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
        val logging = HttpLoggingInterceptor().apply {
            level = if (isDebug) HttpLoggingInterceptor.Level.BODY
            else HttpLoggingInterceptor.Level.NONE
        }

        val baseClient = OkHttpClient.Builder()
            .addInterceptor(logging)
            .connectTimeout(100, TimeUnit.SECONDS)
            .readTimeout(3600, TimeUnit.SECONDS)
            .writeTimeout(120, TimeUnit.SECONDS)
            .callTimeout(3600, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build()

        val retrofitAuth = Retrofit.Builder()
            .baseUrl(Preferences.API_URL)
            .client(baseClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val authServices = retrofitAuth.create(AuthServices::class.java)

        val mainClient = baseClient.newBuilder()
            .addInterceptor(HeaderInterceptor(tokenRepo))
            .addInterceptor(ExpiredRetryInterceptor(tokenRepo, authServices))
            .authenticator(TokenAuthenticator(tokenRepo, authServices))
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl(Preferences.API_URL)
            .client(mainClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        accountServices = retrofit.create(AuthServices::class.java)
        generalServices = retrofit.create(GeneralServices::class.java)
        reaksiServices = retrofit.create(ReaksiServices::class.java)
        selectionServices = retrofit.create(SelectionServices::class.java)
        actionServices = retrofit.create(ActionServices::class.java)
    }
}