package com.fabledsword.minstrel.admin.data

import com.fabledsword.minstrel.api.endpoints.AdminUsersApi
import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody
import com.fabledsword.minstrel.api.endpoints.SetAdminBody
import com.fabledsword.minstrel.api.endpoints.SetAutoApproveBody
import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.models.wire.AdminUserWire
import retrofit2.Retrofit
import retrofit2.create
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Read-through accessor for the admin users list + the four per-user
 * mutations. Mirrors Flutter's `AdminUsersController`. Same
 * no-Room-cache, no-MutationQueue pattern as the other admin slices.
 */
@Singleton
class AdminUsersRepository @Inject constructor(
    retrofit: Retrofit,
) {
    private val api: AdminUsersApi = retrofit.create()

    suspend fun list(): List<AdminUserRef> = api.list().users.map { it.toDomain() }

    suspend fun setAdmin(id: String, isAdmin: Boolean) =
        api.setAdmin(id, SetAdminBody(isAdmin))

    suspend fun setAutoApprove(id: String, autoApprove: Boolean) =
        api.setAutoApprove(id, SetAutoApproveBody(autoApprove))

    suspend fun resetPassword(id: String, newPassword: String) =
        api.resetPassword(id, ResetPasswordBody(newPassword))

    suspend fun delete(id: String) = api.delete(id)
}

private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
    id = id,
    username = username,
    displayName = displayName,
    isAdmin = isAdmin,
    autoApproveRequests = autoApproveRequests,
    createdAt = createdAt,
)
