/*
    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::RequestInfo;
use anyhow::anyhow;
use jellycommon::api::ApiSearchResponse;
use jellylogic::search::search;
use jellyui::{render_page, search::SearchPage};
use rocket::{get, response::content::RawHtml, serde::json::Json, Either};

#[get("/search?<query>&<page>")]
pub async fn r_search(
    ri: RequestInfo,
    query: Option<&str>,
    page: Option<usize>,
) -> MyResult<Either<RawHtml<String>, Json<ApiSearchResponse>>> {
    let r = query
        .map(|query| search(&ri.session, query, page))
        .transpose()?;

    Ok(if ri.accept.is_json() {
        let Some(r) = r else {
            Err(anyhow!("no query"))?
        };
        Either::Right(Json(r))
    } else {
        Either::Left(RawHtml(render_page(
            &SearchPage {
                lang: &ri.lang,
                query: &query.map(|s| s.to_string()),
                r,
            },
            ri.render_info(),
        )))
    })
}
