package com.tomhempel.rbarometer.network

import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

object LoginManager {

    suspend fun login(
        context: Context,
        username: String,
        password: String,
        onMustChangePassword: suspend (tempToken: String, username: String) -> Unit,
        onSuccess: suspend (token: String, username: String, assignedClients: List<String>) -> Unit,
        onError: suspend (String) -> Unit
    ) {
        try {
            val result = withContext(Dispatchers.IO) {
                QuestionnaireApiClient.login(username, password)
            }

            if (result.mustChangePassword) {
                onMustChangePassword(result.token, result.user.ifBlank { username })
                return
            }

            val user = result.user.ifBlank { username }
            onSuccess(result.token, user, result.assignedClientCodes)
        } catch (e: Exception) {
            SyncLog.e("LOGIN", "login failed", e)
            onError(e.message ?: "Login failed")
        }
    }

    suspend fun changePassword(
        context: Context,
        token: String,
        username: String,
        oldPassword: String,
        newPassword: String,
        onSuccess: suspend (token: String, username: String, assignedClients: List<String>) -> Unit,
        onError: suspend (String) -> Unit
    ) {
        try {
            val result = withContext(Dispatchers.IO) {
                QuestionnaireApiClient.changePassword(token, username, oldPassword, newPassword)
            }
            val user = result.user.ifBlank { username }
            onSuccess(result.token, user, result.assignedClientCodes)
        } catch (e: Exception) {
            SyncLog.e("LOGIN", "changePassword failed", e)
            onError(e.message ?: "Password change failed")
        }
    }

    /** @deprecated Use [login] from [AuthActivity] instead. */
    fun loginUserWithCredentials(
        context: Context,
        username: String,
        password: String,
        onSuccess: (String) -> Unit,
        onError: (String) -> Unit
    ) {
        CoroutineScope(Dispatchers.Main).launch {
            login(
                context = context,
                username = username,
                password = password,
                onMustChangePassword = { _, _ ->
                    onError("Password change required. Please use the login screen.")
                },
                onSuccess = { token, user, clients ->
                    withContext(Dispatchers.IO) {
                        QuestionnaireCache.clearAllClientData(context)
                        TokenStore.save(context, token, user)
                        QuestionnaireCache.replaceAssignedClients(context, clients)
                    }
                    onSuccess(token)
                },
                onError = onError
            )
        }
    }
}
