package com.fabledsword.minstrel.admin.data

import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi
import com.fabledsword.minstrel.models.RequestRef
import com.fabledsword.minstrel.models.RequestStatus
import com.fabledsword.minstrel.models.wire.RequestWire
import retrofit2.Retrofit
import retrofit2.create
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Read-through accessor for the admin cross-user requests queue.
 * Mirrors `flutter_client/lib/admin/admin_providers.dart`'s
 * AdminRequestsController.
 *
 * No Room caching — admin actions are infrequent and don't benefit
 * from offline scrollback. `approve` and `reject` fire direct REST
 * (no mutation queue) because operator confirmation is point-and-shoot;
 * if the request fails the UI surfaces the error and rolls back.
 */
@Singleton
class AdminRequestsRepository @Inject constructor(
    retrofit: Retrofit,
) {
    private val api: AdminRequestsApi = retrofit.create()

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

    suspend fun approve(id: String) = api.approve(id)

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

private fun RequestWire.toDomain(): RequestRef = RequestRef(
    id = id,
    userId = userId,
    status = RequestStatus.fromWire(status),
    kind = kind,
    artistName = artistName,
    albumTitle = albumTitle,
    trackTitle = trackTitle,
    requestedAt = requestedAt,
    decidedAt = decidedAt,
    notes = notes,
    importedAlbumCount = importedAlbumCount,
    importedTrackCount = importedTrackCount,
    matchedTrackId = matchedTrackId,
    matchedAlbumId = matchedAlbumId,
    matchedArtistId = matchedArtistId,
)
