package bou.amine.apps.readerforselfossv2.model

import io.ktor.client.call.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.Serializable

@Serializable
class SuccessResponse(val success: Boolean) {
    val isSuccess: Boolean
        get() = success
}

class StatusAndData<T>(val success: Boolean, val data: T? = null) {
    companion object {
        fun <T> succes(d: T): StatusAndData<T> {
            return StatusAndData(true, d)
        }

        fun <T> error(): StatusAndData<T> {
            return StatusAndData(false)
        }
    }
}

suspend fun responseOrSuccessIf404(r: HttpResponse): SuccessResponse {
    return if (r.status === HttpStatusCode.NotFound) {
        SuccessResponse(true)
    } else {
        maybeResponse(r)
    }
}

suspend fun maybeResponse(r: HttpResponse): SuccessResponse {
    return if (r.status.isSuccess()) {
        r.body()
    } else {
        SuccessResponse(false)
    }
}

suspend inline fun <reified T> bodyOrFailure(r: HttpResponse): StatusAndData<T> {
    return if (r.status.isSuccess()) {
        StatusAndData.succes(r.body())
    } else {
        StatusAndData.error()
    }
}