/*
    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::{
    helper::{A, RequestInfo},
    ui::error::MyResult,
};
use jellylogic::{
    admin::log::{get_log_buffer, get_log_stream},
    session::Session,
};
use jellyui::{
    admin::log::{ServerLogPage, render_log_line},
    render_page,
};
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.session.assert_admin()?;
    let messages = get_log_buffer(warnonly)
        .into_iter()
        .map(|l| render_log_line(&l))
        .collect::<Vec<_>>();
    Ok(RawHtml(render_page(
        &ServerLogPage {
            messages: &messages,
            warnonly,
        },
        ri.render_info(),
    )))
}

#[get("/admin/log?stream&<warnonly>&<html>", rank = 1)]
pub fn r_admin_log_stream(
    session: A<Session>,
    ws: WebSocket,
    warnonly: bool,
    html: bool,
) -> Stream!['static] {
    // TODO type problems
    let ok = session.0.assert_admin().is_ok();
    let mut stream = get_log_stream(warnonly);
    Stream! { ws =>
        if !ok {
            yield Message::Text("unauthorized".to_string());
        } else 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());
            }
        }
    }
}
