/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use super::error::MyResult;
use crate::helper::{filter_sort::ANodeFilterSort, RequestInfo, A};
use jellycommon::{
    api::{ApiNodeResponse, NodeFilterSort},
    NodeID,
};
use jellylogic::node::get_node;
use jellyui::{node_page::NodePage, render_page};
use rocket::{get, response::content::RawHtml, serde::json::Json, Either};

#[get("/n/<id>?<parents>&<children>&<filter..>")]
pub async fn r_node(
    ri: RequestInfo,
    id: A<NodeID>,
    filter: Option<ANodeFilterSort>,
    parents: bool,
    children: bool,
) -> MyResult<Either<RawHtml<String>, Json<ApiNodeResponse>>> {
    let filter: Option<NodeFilterSort> = filter.map(Into::into);
    let filter = filter.unwrap_or_default();

    let r = get_node(
        &ri.session,
        id.0,
        !ri.accept.is_json() || children,
        !ri.accept.is_json() || parents,
        filter.clone(),
    )?;

    Ok(if ri.accept.is_json() {
        Either::Right(Json(r))
    } else {
        Either::Left(RawHtml(render_page(
            &NodePage {
                node: &r.node,
                udata: &r.userdata,
                children: &r.children,
                parents: &r.parents,
                similar: &[],
                filter: &filter,
                lang: &ri.lang,
                player: false,
            },
            ri.render_info(),
        )))
    })
}
