package moe.lava.neon.core.repository

import co.touchlab.kermit.Logger
import moe.lava.neon.api.ApiClient
import moe.lava.neon.api.endpoints.getExperiments
import moe.lava.neon.api.endpoints.login
import moe.lava.neon.core.AppSettings

sealed class AuthResponse {
    // TODO: Specify all possible error types here
    data class Failed(val error: Throwable) : AuthResponse()
    data class Success(val token: String) : AuthResponse()
    // TODO
//    data class MFARequested() : AuthResponse()
}

class AuthRepository internal constructor(
    private val settings: AppSettings,
    private val api: ApiClient,
) {
    private val logger = Logger.withTag("neon.core.repo/auth")
    private var token by settings::token
    private var fingerprint by settings::fingerprint

    val loggedIn get() = token != null

    suspend fun login(
        email: String,
        password: String,
    ): AuthResponse {
        try {
            if (fingerprint == null) {
                fingerprint = api.getExperiments().body().fingerprint
            }

            val login = api.login(
                email = email,
                password = password,
                fingerprint = fingerprint!!,
            ).body()
            logger.i { "Login success $login" }
            this.token = login.token

            return AuthResponse.Success(login.token)
        } catch (e: Throwable) {
            return AuthResponse.Failed(e)
        }
    }

    fun login(token: String): String {
        this.token = token
        return token
    }

    fun logout() {
        token = null
    }
}
