Documentation
use {super::*, crate::router::error::RouterError};

pub(crate) enum ServerError {
    Internal(Error),
    NotFound(String),
    BadRequest(String),
    UnprocessableEntity(String),
    ServiceUnavailable(String),
    TooManyRequests(String),
}

pub(crate) type ServerResult<T> = Result<T, ServerError>;

impl IntoResponse for ServerError {
    fn into_response(self) -> Response {
        match self {
            Self::Internal(error) => {
                error!("error serving request: {error}");
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    StatusCode::INTERNAL_SERVER_ERROR
                        .canonical_reason()
                        .unwrap_or_default(),
                )
                    .into_response()
            }
            Self::NotFound(message) => (StatusCode::NOT_FOUND, message).into_response(),
            Self::BadRequest(message) => (StatusCode::BAD_REQUEST, message).into_response(),
            Self::UnprocessableEntity(message) => {
                (StatusCode::UNPROCESSABLE_ENTITY, message).into_response()
            }
            Self::ServiceUnavailable(message) => {
                (StatusCode::SERVICE_UNAVAILABLE, message).into_response()
            }
            Self::TooManyRequests(message) => {
                (StatusCode::TOO_MANY_REQUESTS, message).into_response()
            }
        }
    }
}

impl From<Error> for ServerError {
    fn from(error: Error) -> Self {
        Self::Internal(error)
    }
}

impl From<sysinfo::Error> for ServerError {
    fn from(error: sysinfo::Error) -> Self {
        Self::Internal(error.into())
    }
}

impl From<RouterError> for ServerError {
    fn from(error: RouterError) -> Self {
        match &error {
            RouterError::InvalidHashdays
            | RouterError::HashPriceOverflow
            | RouterError::BelowDustLimit { .. }
            | RouterError::NotABucketOrder { .. }
            | RouterError::InvalidRefundDestination { .. } => Self::BadRequest(error.to_string()),
            RouterError::HashPriceBelowMinimum { .. }
            | RouterError::InsufficientCapacity { .. }
            | RouterError::NoUnspentFunds { .. }
            | RouterError::RefundConstruction { .. } => {
                Self::UnprocessableEntity(error.to_string())
            }
            RouterError::OrderNotFound { .. } => Self::NotFound(error.to_string()),
            RouterError::Halted
            | RouterError::ShuttingDown
            | RouterError::WalletSyncing
            | RouterError::WalletRequired
            | RouterError::WalletPersistence { .. }
            | RouterError::MissingActiveUpstream { .. } => {
                Self::ServiceUnavailable(error.to_string())
            }
            RouterError::OrderRateLimited { .. } => Self::TooManyRequests(error.to_string()),
            RouterError::OrderIdExhausted | RouterError::BlockingTask { .. } => {
                Self::Internal(error.into())
            }
        }
    }
}

pub(crate) trait OptionExt<T> {
    fn ok_or_not_found<F: FnOnce() -> S, S: Into<String>>(self, f: F) -> ServerResult<T>;
}

impl<T> OptionExt<T> for Option<T> {
    fn ok_or_not_found<F: FnOnce() -> S, S: Into<String>>(self, f: F) -> ServerResult<T> {
        match self {
            Some(value) => Ok(value),
            None => Err(ServerError::NotFound(f().into() + " not found")),
        }
    }
}