use super::blog::get_articles_as_links_list;
use crate::html::AppState;
use axum::{response::IntoResponse, routing::get, Extension, Router};

pub fn get_router() -> Router {
    Router::new()
        .route("/hello", get(hello_from_the_server))
        .route("/articles", get(blogs))
        .route("/recentarticles", get(recent_blogs))
}

async fn hello_from_the_server() -> &'static str {
    "Hello!"
}

async fn blogs(state: Extension<AppState>) -> impl IntoResponse {
    let db_pool = &state.db;
    let article_list: Vec<String> = get_articles_as_links_list(db_pool)
        .await
        .expect("couldn't get articles");

    article_list.join("\n")
}

async fn recent_blogs(state: Extension<AppState>) -> impl IntoResponse {
    let db_pool = &state.db;
    let article_list: Vec<String> = get_articles_as_links_list(db_pool)
        .await
        .expect("couldn't get articles");

    let (article_head, _) = article_list.split_at(5);

    article_head.join("\n")
}
