use dropshot::{endpoint, HttpError, HttpResponseOk, RequestContext};
use schemars::JsonSchema;
use serde::Serialize;
use tracing::Instrument;

use std::sync::Arc;

use crate::context::ControllerContext;

/// Version and build information
#[derive(Serialize, JsonSchema)]
struct VersionInfo {
    name: String,
    version: String,
}

/// Fetch version info.
#[endpoint {
    method = GET,
    path = "/version",
}]
#[tracing::instrument(
  skip(rqctx),
  fields(
        http.method=rqctx.request.method().as_str(),
        http.path=rqctx.request.uri().path(),
        http.remote_ip=rqctx.request.remote_addr().ip().to_string(),
        request_id = rqctx.request_id,
    ),
    err(Debug),
)]
pub(crate) async fn version(
    rqctx: RequestContext<Arc<ControllerContext>>,
) -> Result<HttpResponseOk<VersionInfo>, HttpError> {
    let ver = VersionInfo {
        name: env!("CARGO_PKG_NAME").to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
    };

    tracing::info_span!("Hello, span!");

    async move {
        tracing::info!("Someone made a request to /version");
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    }
    .instrument(tracing::info_span!("Let's do the thing...."))
    .await;
    Ok(HttpResponseOk(ver))
}