use std::sync::Arc;

use poem::{
    error::InternalServerError,
    handler,
    web::{Data, Html, Path},
};
use tera::Context;

use crate::{
    app_state::AppState, data::book::Book, handlers::error::SqliteError, templates::TEMPLATES,
};

#[handler]
pub async fn handler(
    id: Path<u64>,
    state: Data<&Arc<AppState>>,
) -> Result<Html<String>, poem::Error> {
    let series = state.calibre.scalar_series(*id).map_err(SqliteError)?;
    let books = state.calibre.series_books(*id).map_err(SqliteError)?;
    let books = books
        .iter()
        .filter_map(|x| Book::full_book(x, &state))
        .collect::<Vec<Book>>();

    let mut context = Context::new();
    context.insert("title", &series.name);
    context.insert("nav", "series");
    context.insert("books", &books);

    TEMPLATES
        .render("book_list", &context)
        .map_err(InternalServerError)
        .map(Html)
}