use bytes::Bytes;
use http::{Request, Response, StatusCode, header};
use http_body::Body;
use http_body_util::{BodyExt, Full};
use thiserror::Error;
use tower::{Service, ServiceExt};

use crate::models::feed::{FeedRequest, FeedResponse};

/// Input to the feed endpoint service
#[derive(Clone, Debug)]
pub struct GetFeedRequest {
    pub base_url: String,
    pub feed_request: FeedRequest,
    pub api_key: Option<String>,
}

#[derive(Debug, Error)]
pub enum GetFeedError {
    #[error("bad url: {0}")]
    BadUrl(String),
    #[error("transport: {0}")]
    Transport(String),
    #[error("http {status}, head: {body_head}")]
    Http {
        status: StatusCode,
        body_head: String,
    },
    #[error("read body")]
    ReadBody,
    #[error("json: {0}")]
    Json(String),
    #[error("request body: {0}")]
    RequestBody(String),
}

/// A Tower service that turns `GetFeedRequest` into a `FeedResponse` by calling:
///   POST {base}/api/feed/v3
///
/// `S` is your HTTP client (e.g. hyper client). It must accept a
/// `Request<Full<Bytes>>` and return a `Response<SB>`.
#[derive(Clone)]
pub struct GetFeed<S> {
    inner: S,
}

impl<S> GetFeed<S> {
    pub fn new(inner: S) -> Self {
        Self { inner }
    }
}

impl<S, SB> Service<GetFeedRequest> for GetFeed<S>
where
    S: Service<Request<Full<Bytes>>, Response = Response<SB>> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: std::error::Error + Send + Sync + 'static,
    SB: Body<Data = Bytes> + Send + 'static,
    SB::Error: std::error::Error + Send + Sync + 'static,
{
    type Response = FeedResponse;
    type Error = GetFeedError;
    type Future = futures_util::future::BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner
            .poll_ready(cx)
            .map_err(|e| GetFeedError::Transport(e.to_string()))
    }

    fn call(&mut self, req: GetFeedRequest) -> Self::Future {
        let client = self.inner.clone();
        let url = format!("{}/api/feed/v3", req.base_url.trim_end_matches('/'));

        // Serialize request body
        let body_bytes = match serde_json::to_vec(&req.feed_request) {
            Ok(b) => b,
            Err(e) => {
                return Box::pin(async move { Err(GetFeedError::RequestBody(e.to_string())) });
            }
        };

        let mut builder = Request::builder()
            .method("POST")
            .uri(url.clone())
            .header(header::CONTENT_TYPE, "application/json");

        if let Some(k) = req.api_key.clone() {
            let headers = builder.headers_mut().expect("request builder usable");
            headers.insert(
                header::AUTHORIZATION,
                format!("Bearer {k}").parse().expect("valid Authorization"),
            );
            headers.insert("X-Api-Key", k.parse().expect("valid X-Api-Key"));
        }

        let request = match builder.body(Full::new(Bytes::from(body_bytes))) {
            Ok(r) => r,
            Err(e) => return Box::pin(async move { Err(GetFeedError::BadUrl(e.to_string())) }),
        };

        Box::pin(async move {
            let resp = client
                .oneshot(request)
                .await
                .map_err(|e| GetFeedError::Transport(e.to_string()))?;

            let status = resp.status();
            let body_bytes = resp
                .into_body()
                .collect()
                .await
                .map_err(|_| GetFeedError::ReadBody)?
                .to_bytes();

            if !status.is_success() {
                let head = String::from_utf8_lossy(&body_bytes)
                    .chars()
                    .take(400)
                    .collect::<String>();
                return Err(GetFeedError::Http {
                    status,
                    body_head: head,
                });
            }

            serde_json::from_slice::<FeedResponse>(&body_bytes)
                .map_err(|e| GetFeedError::Json(e.to_string()))
        })
    }
}
