/*
    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::{
    logger::{get_log_buffer, get_log_stream},
    request_info::RequestInfo,
    routes::error::MyResult,
};
use jellyui::components::admin_log::{ServerLogPage, render_log_line};
use rocket::{get, response::content::RawHtml};
use rocket_ws::{Message, Stream, WebSocket};
use serde_json::json;

#[get("/admin/log?<warnonly>", rank = 2)]
pub fn r_admin_log(ri: RequestInfo, warnonly: bool) -> MyResult<RawHtml<String>> {
    ri.require_admin()?;
    let messages = get_log_buffer(warnonly)
        .into_iter()
        .map(|l| render_log_line(&l))
        .collect::<Vec<_>>();

    Ok(ri.respond_ui(&ServerLogPage {
        ri: &ri.render_info(),
        messages: &messages,
        warnonly,
    }))
}

#[get("/admin/log?stream&<warnonly>&<html>", rank = 1)]
pub fn r_admin_log_stream(
    ri: RequestInfo,
    ws: WebSocket,
    warnonly: bool,
    html: bool,
) -> MyResult<Stream!['static]> {
    ri.require_admin()?;
    let mut stream = get_log_stream(warnonly);
    Ok({
        Stream! { ws =>
            if html {
                let _ = ws;
                while let Ok(line) = stream.recv().await {
                    yield Message::Text(render_log_line(&line));
                }
            } else {
                let _ = ws;
                while let Ok(line) = stream.recv().await {
                    yield Message::Text(json!(line).to_string());
                }
            }
        }
    })
}
