use serde_json::json;
use web_sys::{window, CustomEvent, CustomEventInit};

pub(crate) fn dispatch_editor_upload_request(kind: &str, accept: &str) -> Result<(), String> {
    let win = window().ok_or_else(|| "当前浏览器窗口不可用".to_string())?;
    let detail = json!({
        "kind": kind,
        "accept": accept,
        "multiple": true,
        "insertIntoEditor": true,
    });
    let detail =
        serde_wasm_bindgen::to_value(&detail).map_err(|err| format!("构造上传请求失败：{err}"))?;
    let init = CustomEventInit::new();
    init.set_detail(&detail);
    let event = CustomEvent::new_with_event_init_dict("mnote:editor-upload-request", &init)
        .map_err(|_| "构造上传事件失败".to_string())?;
    win.dispatch_event(&event)
        .map(|_| ())
        .map_err(|_| "派发上传事件失败".to_string())
}
