// Phase 9. Thin filesystem write command for the save-dialog path.
//
// Path safety: the caller is expected to obtain `path` via the OS save
// dialog (tauri-plugin-dialog). We do not validate traversal, extension,
// or parent-dir existence beyond what the OS filesystem reports — the
// dialog already constrains the user's choice to what they can write to.

/// Write UTF-8 text to a user-chosen path. Errors propagate the OS
/// message verbatim wrapped with the path so the toast on the frontend
/// is actionable ("Failed to write …: Permission denied" rather than a
/// bare error code).
#[tauri::command]
pub async fn write_text_file_cmd(path: String, contents: String) -> Result<(), String> {
    tokio::fs::write(&path, contents)
        .await
        .map_err(|e| format!("Failed to write {path}: {e}"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn write_text_file_roundtrips_utf8() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("out.md").display().to_string();
        write_text_file_cmd(path.clone(), "hello\nwørld\n".into())
            .await
            .expect("write");

        let round = tokio::fs::read_to_string(&path).await.expect("read");
        assert_eq!(round, "hello\nwørld\n");
    }

    #[tokio::test]
    async fn write_text_file_errors_on_bad_parent() {
        let result = write_text_file_cmd(
            "/definitely-not-a-real-path-kon-phase9/out.md".into(),
            "x".into(),
        )
        .await;
        assert!(result.is_err(), "expected error for nonexistent parent");
    }
}
