use crate::database::page::Page;
use askama::Template;
use axum::{
    http::StatusCode,
    response::{Html, IntoResponse, Response},
};
use sqlx::PgPool;

pub mod api;
pub mod blog;
pub mod garden;
pub mod root;

#[derive(Clone)]
pub struct AppState {
    pub db: PgPool,
}

/// A wrapper type that we'll use to encapsulate HTML parsed by askama into valid HTML for axum to serve.
pub struct HtmlTemplate<T>(pub T);

/// Allows us to convert Askama HTML templates into valid HTML for axum to serve in the response.
impl<T> IntoResponse for HtmlTemplate<T>
where
    T: Template,
{
    fn into_response(self) -> Response {
        // Attempt to render the template with askama
        match self.0.render() {
            // If we're able to successfully parse and aggregate the template, serve it
            Ok(html) => Html(html).into_response(),
            // If we're not, return an error or some bit of fallback HTML
            Err(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to render template. Error: {}", err),
            )
                .into_response(),
        }
    }
}

#[derive(Template)]
#[template(path = "article.html")]
pub struct ArticleTemplate {
    footer: String,
    content: String,
}

#[derive(Template)]
#[template(path = "page.html")]
pub struct PageTemplate {
    content: String,
}

pub async fn get_page(db: &PgPool, path: &str) -> Result<impl IntoResponse, StatusCode> {
    let reference: String = path.to_string();
    let page: Page = match Page::read_by_reference(db, &reference).await {
        Ok(a) => *a,
        Err(_) => return Err(StatusCode::NOT_FOUND),
    };

    let template = PageTemplate {
        content: page.content,
    };
    Ok(HtmlTemplate(template))
}
