package com.ponzischeme89.memby.update

import com.ponzischeme89.memby.data.model.GatewayUpdate
import com.ponzischeme89.memby.data.remote.GatewayServiceFactory
import kotlinx.coroutines.CancellationException

/**
 * App-level update client, deliberately independent of profiles and saved sessions.
 *
 * The gateway endpoint is public and the Retrofit client below never receives a bearer
 * token. This makes an update check safe before sign-in and prevents update failures from
 * invalidating, replacing, or otherwise coupling themselves to a viewer's credentials.
 */
class ServerUpdateService private constructor(
    private val checkRemote: (suspend () -> GatewayUpdate)?,
) {
    suspend fun check(): Result<GatewayUpdate?> {
        val remote = checkRemote ?: return Result.success(null)
        return try {
            Result.success(remote().takeIf { it.isActionable })
        } catch (cancelled: CancellationException) {
            throw cancelled
        } catch (failure: Throwable) {
            Result.failure(failure)
        }
    }

    companion object {
        fun create(gatewayUrl: String?): ServerUpdateService {
            val api = gatewayUrl?.let { GatewayServiceFactory.create(it) { null } }
            return ServerUpdateService(api?.let { { it.updateStatus() } })
        }

        internal fun forTest(check: suspend () -> GatewayUpdate): ServerUpdateService =
            ServerUpdateService(check)
    }
}
