package com.devlab.app.util

import com.devlab.app.data.api.RetrofitClient
import com.devlab.app.data.model.AppVersionResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

data class UpdateInfo(
    val hasUpdate: Boolean,
    val version: String,
    val apkUrl: String,
    val forceUpdate: Boolean,
    val releaseNotes: String
)

class UpdateChecker(private val currentVersion: String) {

    suspend fun check(): UpdateInfo = withContext(Dispatchers.IO) {
        try {
            val service = RetrofitClient.getUnauthenticatedService()
            val response = service.checkVersion()
            if (response.success && response.data != null) {
                val remoteVersion = parseVersion(response.data.version)
                val localVersion = parseVersion(currentVersion)
                val hasUpdate = remoteVersion > localVersion

                UpdateInfo(
                    hasUpdate = hasUpdate,
                    version = response.data.version,
                    apkUrl = response.data.apk_url,
                    forceUpdate = response.data.force_update,
                    releaseNotes = response.data.release_notes
                )
            } else {
                UpdateInfo(false, "", "", false, "")
            }
        } catch (_: Exception) {
            UpdateInfo(false, "", "", false, "")
        }
    }

    private fun parseVersion(version: String): Triple<Int, Int, Int> {
        val parts = version.split(".").mapNotNull { it.toIntOrNull() }
        return Triple(
            parts.getOrElse(0) { 0 },
            parts.getOrElse(1) { 0 },
            parts.getOrElse(2) { 0 }
        )
    }

    private operator fun Triple<Int, Int, Int>.compareTo(other: Triple<Int, Int, Int>): Int {
        return when {
            first != other.first -> first.compareTo(other.first)
            second != other.second -> second.compareTo(other.second)
            else -> third.compareTo(other.third)
        }
    }
}
