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

use crate::models::playlist::{
    LikedPlaylistsResponse, PlaylistDetailsResponse, PlaylistsWithClipStatusResponse,
    UserPlaylistsResponse,
};

// Macro to reduce boilerplate for GET services
macro_rules! impl_get_service {
    ($service:ident, $request:ident, $error:ident, $response:ident, $endpoint:expr) => {
        #[derive(Clone)]
        pub struct $service<S> {
            inner: S,
        }

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

        impl<S, SB> Service<$request> for $service<S>
        where
            S: Service<Request<Empty<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 = $response;
            type Error = $error;
            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| $error::Transport(e.to_string()))
            }

            fn call(&mut self, req: $request) -> Self::Future {
                let client = self.inner.clone();
                let url = $endpoint(&req);

                let mut builder = Request::builder().method("GET").uri(&url);

                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(Empty::new()) {
                    Ok(r) => r,
                    Err(e) => return Box::pin(async move { Err($error::BadUrl(e.to_string())) }),
                };

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

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

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

                    serde_json::from_slice::<$response>(&body_bytes)
                        .map_err(|e| $error::Json(e.to_string()))
                })
            }
        }
    };
}

// =============================================================================
// GET LIKED PLAYLISTS
// =============================================================================

#[derive(Clone, Debug)]
pub struct GetLikedPlaylistsRequest {
    pub base_url: String,
    pub page: Option<i32>,
    pub api_key: Option<String>,
}

#[derive(Debug, Error)]
pub enum GetLikedPlaylistsError {
    #[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),
}

impl_get_service!(
    GetLikedPlaylists,
    GetLikedPlaylistsRequest,
    GetLikedPlaylistsError,
    LikedPlaylistsResponse,
    |req: &GetLikedPlaylistsRequest| {
        let mut url = format!(
            "{}/api/playlist/liked_playlist",
            req.base_url.trim_end_matches('/')
        );
        if let Some(page) = req.page {
            url.push_str(&format!("?page={}", page));
        }
        url
    }
);

// =============================================================================
// GET USER PLAYLISTS (ME)
// =============================================================================

#[derive(Clone, Debug)]
pub struct GetUserPlaylistsRequest {
    pub base_url: String,
    pub page: Option<i32>,
    pub query: Option<String>,
    pub show_trashed: Option<bool>,
    pub show_liked: Option<bool>,
    pub show_sharelist: Option<bool>,
    pub api_key: Option<String>,
}

#[derive(Debug, Error)]
pub enum GetUserPlaylistsError {
    #[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),
}

impl_get_service!(
    GetUserPlaylists,
    GetUserPlaylistsRequest,
    GetUserPlaylistsError,
    UserPlaylistsResponse,
    |req: &GetUserPlaylistsRequest| {
        let mut url = format!("{}/api/playlist/me", req.base_url.trim_end_matches('/'));
        let mut params = Vec::new();
        if let Some(page) = req.page {
            params.push(format!("page={}", page));
        }
        if let Some(query) = &req.query {
            params.push(format!("query={}", query));
        }
        if let Some(show_trashed) = req.show_trashed {
            params.push(format!("show_trashed={}", show_trashed));
        }
        if let Some(show_liked) = req.show_liked {
            params.push(format!("show_liked={}", show_liked));
        }
        if let Some(show_sharelist) = req.show_sharelist {
            params.push(format!("show_sharelist={}", show_sharelist));
        }
        if !params.is_empty() {
            url.push('?');
            url.push_str(&params.join("&"));
        }
        url
    }
);

// =============================================================================
// GET PLAYLISTS WITH CLIP STATUS
// =============================================================================

#[derive(Clone, Debug)]
pub struct GetPlaylistsWithClipStatusRequest {
    pub base_url: String,
    pub clip_id: String,
    pub page: Option<i32>,
    pub api_key: Option<String>,
}

#[derive(Debug, Error)]
pub enum GetPlaylistsWithClipStatusError {
    #[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),
}

impl_get_service!(
    GetPlaylistsWithClipStatus,
    GetPlaylistsWithClipStatusRequest,
    GetPlaylistsWithClipStatusError,
    PlaylistsWithClipStatusResponse,
    |req: &GetPlaylistsWithClipStatusRequest| {
        let mut url = format!(
            "{}/api/playlist/me/clip_status?clip_id={}",
            req.base_url.trim_end_matches('/'),
            &req.clip_id
        );
        if let Some(page) = req.page {
            url.push_str(&format!("&page={}", page));
        }
        url
    }
);

// =============================================================================
// GET SPECIFIC PLAYLIST
// =============================================================================

#[derive(Clone, Debug)]
pub struct GetPlaylistRequest {
    pub base_url: String,
    pub playlist_id: String,
    pub page: Option<i32>,
    pub cursor: Option<String>,
    pub api_key: Option<String>,
}

#[derive(Debug, Error)]
pub enum GetPlaylistError {
    #[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),
}

impl_get_service!(
    GetPlaylist,
    GetPlaylistRequest,
    GetPlaylistError,
    PlaylistDetailsResponse,
    |req: &GetPlaylistRequest| {
        let mut url = format!(
            "{}/api/playlist/{}",
            req.base_url.trim_end_matches('/'),
            &req.playlist_id
        );
        let mut params = Vec::new();
        if let Some(page) = req.page {
            params.push(format!("page={}", page));
        }
        if let Some(cursor) = &req.cursor {
            params.push(format!("cursor={}", cursor));
        }
        if !params.is_empty() {
            url.push('?');
            url.push_str(&params.join("&"));
        }
        url
    }
);
