use tauri::command;

#[cfg(target_os = "windows")]
use windows::{
    core::{Result as WindowsResult, HSTRING},
    Data::Xml::Dom::*,
    UI::Notifications::*,
};

#[cfg(target_os = "windows")]
#[command]
pub async fn send_windows_toast(title: String, body: String) -> Result<(), String> {
    show_toast_notification(&title, &body)
        .map_err(|e| format!("Failed to show toast notification: {}", e))
}

#[cfg(target_os = "windows")]
fn show_toast_notification(title: &str, body: &str) -> WindowsResult<()> {
    // Create the XML for the toast notification
    let toast_xml = format!(
        r#"<toast>
            <visual>
                <binding template="ToastGeneric">
                    <text>{}</text>
                    <text>{}</text>
                </binding>
            </visual>
            <audio src="ms-winsoundevent:Notification.Default" />
        </toast>"#,
        escape_xml(title),
        escape_xml(body)
    );

    let xml_doc = XmlDocument::new()?;
    xml_doc.LoadXml(&HSTRING::from(toast_xml))?;

    // Create the toast notification
    let toast = ToastNotification::CreateToastNotification(&xml_doc)?;

    // Create a toast notifier with an application ID
    let notifier =
        ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from("Hikari Desktop"))?;

    // Show the notification
    notifier.Show(&toast)?;

    Ok(())
}

#[cfg(target_os = "windows")]
fn escape_xml(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

// Stub for non-Windows platforms
#[cfg(not(target_os = "windows"))]
#[command]
pub async fn send_windows_toast(_title: String, _body: String) -> Result<(), String> {
    Err("Windows toast notifications are only available on Windows".to_string())
}
