package com.fabledsword.minstrel.settings.data

import com.fabledsword.minstrel.api.endpoints.ChangePasswordRequest
import com.fabledsword.minstrel.api.endpoints.ListenBrainzPutBody
import com.fabledsword.minstrel.api.endpoints.MeApi
import com.fabledsword.minstrel.api.endpoints.UpdateProfileRequest
import com.fabledsword.minstrel.models.ListenBrainzStatus
import com.fabledsword.minstrel.models.MyProfile
import com.fabledsword.minstrel.models.wire.ListenBrainzStatusWire
import com.fabledsword.minstrel.models.wire.MyProfileWire
import retrofit2.Retrofit
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Thin facade over the `/api/me` endpoints for the Settings Profile
 * and Password cards. No Room caching — the Settings card fetches
 * on screen mount and writes go straight to the server. Network
 * errors surface to the caller for UI snackbar; no offline-queue
 * path because changing your own password offline doesn't make sense.
 */
@Singleton
class MeRepository @Inject constructor(retrofit: Retrofit) {
    private val api: MeApi = retrofit.create(MeApi::class.java)

    suspend fun getProfile(): MyProfile = api.getProfile().toDomain()

    suspend fun updateProfile(displayName: String?, email: String?): MyProfile =
        api.updateProfile(
            UpdateProfileRequest(displayName = displayName, email = email),
        ).toDomain()

    suspend fun changePassword(current: String, next: String) {
        api.changePassword(
            ChangePasswordRequest(currentPassword = current, newPassword = next),
        )
    }

    suspend fun getListenBrainz(): ListenBrainzStatus =
        api.getListenBrainz().toDomain()

    suspend fun setListenBrainzToken(token: String): ListenBrainzStatus =
        api.setListenBrainz(ListenBrainzPutBody(token = token)).toDomain()

    suspend fun setListenBrainzEnabled(enabled: Boolean): ListenBrainzStatus =
        api.setListenBrainz(ListenBrainzPutBody(enabled = enabled)).toDomain()
}

private fun MyProfileWire.toDomain(): MyProfile = MyProfile(
    id = id,
    username = username,
    displayName = displayName,
    email = email,
    isAdmin = isAdmin,
)

private fun ListenBrainzStatusWire.toDomain(): ListenBrainzStatus = ListenBrainzStatus(
    enabled = enabled,
    tokenSet = tokenSet,
    lastScrobbledAt = lastScrobbledAt,
)
