/*
    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 crate::{DATABASE, filter_sort::filter_and_sort_nodes, session::Session};
use anyhow::Result;
use jellycommon::{
    Visibility,
    api::{ApiItemsResponse, NodeFilterSort, SortOrder, SortProperty},
};

pub fn all_items(
    session: &Session,
    page: Option<usize>,
    filter: NodeFilterSort,
) -> Result<ApiItemsResponse> {
    let mut items = DATABASE.list_nodes_with_udata(session.user.name.as_str())?;

    items.retain(|(n, _)| matches!(n.visibility, Visibility::Visible));

    filter_and_sort_nodes(
        &filter,
        (SortProperty::Title, SortOrder::Ascending),
        &mut items,
    );

    let page_size = 100;
    let page = page.unwrap_or(0);
    let offset = page * page_size;
    let from = offset.min(items.len());
    let to = (offset + page_size).min(items.len());
    let max_page = items.len().div_ceil(page_size);
    Ok(ApiItemsResponse {
        count: items.len(),
        pages: max_page,
        items: items[from..to].to_vec(),
    })
}
