use std::pin::Pin;

use axum::http::{
	HeaderMap, HeaderValue, StatusCode,
	header::{self, InvalidHeaderValue},
};

use crate::{Rendered, RequestContext, Servable};

pub struct Redirect {
	to: HeaderValue,
}

impl Redirect {
	pub fn new(to: impl Into<String>) -> Result<Self, InvalidHeaderValue> {
		Ok(Self {
			to: HeaderValue::from_str(&to.into())?,
		})
	}
}

impl Servable for Redirect {
	fn render<'a>(
		&'a self,
		_ctx: &'a RequestContext,
	) -> Pin<Box<dyn Future<Output = Rendered> + 'a + Send + Sync>> {
		Box::pin(async {
			let mut headers = HeaderMap::with_capacity(1);
			headers.append(header::LOCATION, self.to.clone());

			return Rendered {
				code: StatusCode::PERMANENT_REDIRECT,
				headers,
				body: Vec::new(),
				ttl: None,
			};
		})
	}
}
