use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

use axum::{
    body::Body,
    http::{Request, Response, StatusCode},
};
use tower::{Layer, Service};

use crate::registry;

/// Tower middleware layer that adds a `GET /__studio/routes` endpoint
/// returning the JSON route registry. All other requests pass through.
#[derive(Clone, Default)]
pub struct StudioLayer;

impl StudioLayer {
    pub fn new() -> Self {
        Self
    }
}

impl<S> Layer<S> for StudioLayer {
    type Service = StudioService<S>;
    fn layer(&self, inner: S) -> Self::Service {
        StudioService { inner }
    }
}

#[derive(Clone)]
pub struct StudioService<S> {
    inner: S,
}

type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

impl<S, E> Service<Request<Body>> for StudioService<S>
where
    S: Service<Request<Body>, Response = Response<Body>, Error = E> + Clone + Send + 'static,
    S::Future: Send + 'static,
    E: Send + 'static,
{
    type Response = Response<Body>;
    type Error = E;
    type Future = BoxFuture<Result<Self::Response, E>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), E>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        if req.uri().path() == "/__studio/routes" {
            let routes = registry::list();
            let json = serde_json::to_string(&routes).unwrap_or_else(|_| "[]".to_string());
            return Box::pin(async move {
                Ok(Response::builder()
                    .status(StatusCode::OK)
                    .header("content-type", "application/json")
                    .body(Body::from(json))
                    .unwrap())
            });
        }

        let future = self.inner.call(req);
        Box::pin(future)
    }
}
