/*
    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 std::time::Duration;

use crate::{
    helper::{A, RequestInfo},
    ui::error::MyResult,
};
use jellycommon::routes::u_admin_import;
use jellyimport::{
    is_importing,
    reporting::{IMPORT_ERRORS, IMPORT_PROGRESS},
};
use jellylogic::{admin::do_import, session::Session};
use jellyui::{admin::import::AdminImportPage, locale::tr, render_page};
use rocket::{
    get, post,
    request::FlashMessage,
    response::{Flash, Redirect, content::RawHtml},
};
use rocket_ws::{Message, Stream, WebSocket};
use tokio::time::sleep;

#[get("/admin/import", rank = 2)]
pub async fn r_admin_import(
    ri: RequestInfo,
    flash: Option<FlashMessage<'_>>,
) -> MyResult<RawHtml<String>> {
    ri.session.assert_admin()?;

    let last_import_err = IMPORT_ERRORS.read().await.clone();
    Ok(RawHtml(render_page(
        &AdminImportPage {
            busy: is_importing(),
            flash: &flash.map(FlashMessage::into_inner),
            lang: &ri.lang,
            last_import_err: &last_import_err,
        },
        ri.render_info(),
    )))
}

#[post("/admin/import?<incremental>")]
pub async fn r_admin_import_post(ri: RequestInfo, incremental: bool) -> MyResult<Flash<Redirect>> {
    ri.session.assert_admin()?;
    do_import(&ri.session, incremental).await?;
    Ok(Flash::success(
        Redirect::to(u_admin_import()),
        tr(ri.lang, "admin.import_success"),
    ))
}

#[get("/admin/import", rank = 1)]
pub fn r_admin_import_stream(_session: A<Session>, ws: WebSocket) -> Stream!['static] {
    Stream! { ws =>
        loop {
            let Some(p) = IMPORT_PROGRESS.read().await.clone() else {
                break;
            };
            yield Message::Text(serde_json::to_string(&p).unwrap());
            sleep(Duration::from_secs_f32(0.05)).await;
        }
        yield Message::Text("done".to_string());
        let _ = ws;
    }
}
