asyncapi-rust-models 0.5.0

Runtime data structures for asyncapi-rust (AsyncAPI 3.0 spec models)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! Runtime data structures for AsyncAPI 3.0 specifications
//!
//! This crate provides Rust types that represent [AsyncAPI 3.0](https://www.asyncapi.com/docs/reference/specification/v3.0.0)
//! specification objects. These types are used by the proc macros to generate
//! specifications at compile time and can also be constructed manually.
//!
//! ## Overview
//!
//! The main types mirror the AsyncAPI 3.0 specification structure:
//!
//! - [`AsyncApiSpec`] - Root specification object
//! - [`Info`] - General API information
//! - [`Server`] - Server connection details
//! - [`Channel`] - Communication channels
//! - [`Operation`] - Send/receive operations
//! - [`Message`] - Message definitions
//! - [`Schema`] - JSON Schema definitions
//! - [`Components`] - Reusable components
//!
//! ## Serialization
//!
//! All types implement [`serde::Serialize`] and [`serde::Deserialize`] for JSON
//! serialization, following the AsyncAPI 3.0 specification's JSON Schema.
//!
//! ## Example
//!
//! ```rust
//! use asyncapi_rust_models::*;
//! use indexmap::IndexMap;
//!
//! // Create a simple AsyncAPI specification
//! let spec = AsyncApiSpec {
//!     asyncapi: "3.0.0".to_string(),
//!     info: Info {
//!         title: "My API".to_string(),
//!         version: "1.0.0".to_string(),
//!         description: Some("A simple API".to_string()),
//!     },
//!     servers: None,
//!     channels: None,
//!     operations: None,
//!     components: None,
//! };
//!
//! // Serialize to JSON
//! let json = serde_json::to_string_pretty(&spec).unwrap();
//! ```

#![deny(missing_docs)]
#![warn(clippy::all)]

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

/// AsyncAPI 3.0 Specification
///
/// Root document object representing a complete AsyncAPI specification.
///
/// This is the top-level object that contains all information about an API,
/// including servers, channels, operations, and reusable components.
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::*;
///
/// let spec = AsyncApiSpec {
///     asyncapi: "3.0.0".to_string(),
///     info: Info {
///         title: "My WebSocket API".to_string(),
///         version: "1.0.0".to_string(),
///         description: Some("Real-time messaging API".to_string()),
///     },
///     servers: None,
///     channels: None,
///     operations: None,
///     components: None,
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsyncApiSpec {
    /// AsyncAPI version (e.g., "3.0.0")
    pub asyncapi: String,

    /// General information about the API
    pub info: Info,

    /// Server connection details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub servers: Option<IndexMap<String, Server>>,

    /// Available channels (communication paths)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channels: Option<IndexMap<String, Channel>>,

    /// Operations (send/receive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operations: Option<IndexMap<String, Operation>>,

    /// Reusable components (messages, schemas, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub components: Option<Components>,
}

/// API information object
///
/// Contains general metadata about the API such as title, version, and description.
/// This information is displayed in documentation tools and helps users understand
/// the purpose and version of the API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Info {
    /// API title
    ///
    /// A human-readable name for the API (e.g., "Chat WebSocket API")
    pub title: String,

    /// API version
    ///
    /// The version of the API (e.g., "1.0.0"). Should follow semantic versioning.
    pub version: String,

    /// API description
    ///
    /// A longer description of the API's purpose and functionality (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Server connection information
///
/// Defines connection details for a server that hosts the API. Multiple servers
/// can be defined to support different environments (production, staging, development).
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::{Server, ServerVariable};
/// use indexmap::IndexMap;
///
/// let mut variables = IndexMap::new();
/// variables.insert("userId".to_string(), ServerVariable {
///     description: Some("User ID for connection".to_string()),
///     default: None,
///     enum_values: None,
///     examples: Some(vec!["12".to_string(), "13".to_string()]),
/// });
///
/// let server = Server {
///     host: "chat.example.com:443".to_string(),
///     protocol: "wss".to_string(),
///     pathname: Some("/api/ws/{userId}".to_string()),
///     description: Some("Production WebSocket server".to_string()),
///     variables: Some(variables),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Server {
    /// Server URL or host
    ///
    /// The hostname or URL where the server is hosted. May include port number.
    /// Examples: "localhost:8080", "api.example.com", "ws.example.com:443"
    pub host: String,

    /// Protocol (e.g., "wss", "ws", "grpc")
    ///
    /// The protocol used to communicate with the server.
    /// Common values: "ws" (WebSocket), "wss" (WebSocket Secure), "grpc", "mqtt"
    pub protocol: String,

    /// Optional pathname for the server URL
    ///
    /// The pathname to append to the host. Can contain variables in curly braces (e.g., "/api/ws/{userId}")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pathname: Option<String>,

    /// Server description
    ///
    /// An optional human-readable description of the server's purpose or environment
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Server variables
    ///
    /// A map of variable name to ServerVariable definition for variables used in the pathname
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variables: Option<IndexMap<String, ServerVariable>>,

    /// Protocol specific bindings.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub bindings: Option<ServerBindings>,
}

/// Protocol specific server bindings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerBindings {
    /// Mqtt protocol specific bindings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mqtt: Option<MqttServerBindings>,
}

/// Mqtt last will structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MqttLastWill {
    /// The topic where the Last Will and Testament message will be sent.
    pub topic: String,

    /// Defines how hard the broker/client will try to ensure that the Last Will and Testament message is received. Its value MUST be either 0, 1 or 2.
    pub qos: u8,

    /// Last Will message.
    pub message: String,

    /// Whether the broker should retain the Last Will and Testament message or not.
    pub retain: bool,
}

/// Represents mqtt binding properties which can be either a number or a json schema like sessionExpiryInterval or maximumPacketSize
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MqttBindingNumValue {
    /// The value variant
    Value(u32),
    /// The schema variant
    Schema(Schema),
}

/// Mqtt server binding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MqttServerBindings {
    /// The client identifier.
    #[serde(skip_serializing_if = "Option::is_none", rename = "clientId")]
    pub client_id: Option<String>,

    /// Whether to create a persistent connection or not. When false,
    /// the connection will be persistent. This is called clean start in MQTTv5.
    #[serde(skip_serializing_if = "Option::is_none", rename = "cleanSession")]
    pub clean_session: Option<bool>,

    /// Last Will and Testament configuration. topic, qos, message and retain are properties of this object as shown below.
    #[serde(skip_serializing_if = "Option::is_none", rename = "lastWill")]
    pub last_will: Option<MqttLastWill>,

    /// Interval in seconds of the longest period of time the broker and the client can endure without sending a message.
    #[serde(skip_serializing_if = "Option::is_none", rename = "keepAlive")]
    pub keep_alive: Option<u32>,

    /// Interval in seconds or a Schema Object containing the definition of the interval. The broker maintains a session for a disconnected client until this interval expires.
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "sessionExpiryInterval"
    )]
    pub session_expiry_interval: Option<MqttBindingNumValue>,

    /// Number of bytes or a Schema Object representing the maximum packet size the client is willing to accept.
    #[serde(skip_serializing_if = "Option::is_none", rename = "maximumPacketSize")]
    pub max_packet_size: Option<MqttBindingNumValue>,

    /// The version of this binding. If omitted, "latest" MUST be assumed.
    #[serde(skip_serializing_if = "Option::is_none", rename = "bindingVersion")]
    pub binding_version: Option<String>,
}

/// Server variable definition
///
/// Defines a variable that can be used in the server pathname. Variables are
/// substituted at runtime with actual values.
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::ServerVariable;
///
/// let user_id_var = ServerVariable {
///     description: Some("Authenticated user ID".to_string()),
///     default: None,
///     enum_values: None,
///     examples: Some(vec!["12".to_string(), "13".to_string()]),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerVariable {
    /// Variable description
    ///
    /// Human-readable description of what this variable represents
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Default value
    ///
    /// The default value to use if no value is provided
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Enumeration of allowed values
    ///
    /// If specified, only these values are valid for this variable
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<String>>,

    /// Example values
    ///
    /// A list of example values for documentation purposes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub examples: Option<Vec<String>>,
}

/// Communication channel
///
/// Represents a communication path through which messages are exchanged.
/// Channels define where messages are sent and received (e.g., WebSocket endpoints,
/// message queue topics, gRPC methods).
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::{Channel, Parameter};
/// use indexmap::IndexMap;
///
/// let mut parameters = IndexMap::new();
/// parameters.insert("userId".to_string(), Parameter {
///     description: Some("User ID for this WebSocket connection".to_string()),
///     default: None,
///     enum_values: None,
///     examples: Some(vec!["42".to_string(), "100".to_string()]),
///     location: None,
/// });
///
/// let channel = Channel {
///     address: Some("/ws/chat/{userId}".to_string()),
///     messages: None,
///     parameters: Some(parameters),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Channel {
    /// Channel address/path
    ///
    /// The location where this channel is available. For WebSocket, this is typically
    /// the WebSocket path (e.g., "/ws/chat"). For other protocols, this could be a
    /// topic name, queue name, or method path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<String>,

    /// Messages available on this channel
    ///
    /// A map of message identifiers to message definitions or references.
    /// Messages define the structure of data that flows through this channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub messages: Option<IndexMap<String, MessageRef>>,

    /// Channel parameters
    ///
    /// A map of parameter names to their schema definitions for variables used in the address
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<IndexMap<String, Parameter>>,
}

/// Channel parameter definition
///
/// Defines a parameter that can be used in the channel address, following the
/// [AsyncAPI 3.0 Parameter Object](https://www.asyncapi.com/docs/reference/specification/v3.0.0#parameterObject).
///
/// Note: AsyncAPI 3.0 removed the `schema` property from Parameter (present in 2.x).
/// Parameters now use `description`, `default`, `enum`, `examples`, and `location`.
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::Parameter;
///
/// let user_id_param = Parameter {
///     description: Some("User ID for this WebSocket connection".to_string()),
///     default: Some("0".to_string()),
///     enum_values: None,
///     examples: Some(vec!["42".to_string(), "100".to_string()]),
///     location: None,
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Parameter {
    /// Human-readable description of what this parameter represents
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Default value for this parameter
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Enumeration of allowed values for this parameter
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<String>>,

    /// Example values for this parameter
    #[serde(skip_serializing_if = "Option::is_none")]
    pub examples: Option<Vec<String>>,

    /// Runtime expression specifying the location of the parameter value
    ///
    /// See <https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression>
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
}

/// Reference to a message definition
///
/// Messages can be defined either inline or as references to reusable components.
/// This enum supports both patterns, following the AsyncAPI 3.0 specification.
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::{MessageRef, Message};
///
/// // Reference to a component message
/// let ref_msg = MessageRef::Reference {
///     reference: "#/components/messages/ChatMessage".to_string(),
/// };
///
/// // Inline message definition
/// let inline_msg = MessageRef::Inline(Box::new(Message {
///     name: Some("ChatMessage".to_string()),
///     title: Some("Chat Message".to_string()),
///     summary: Some("A chat message".to_string()),
///     description: None,
///     content_type: Some("application/json".to_string()),
///     payload: None,
///     ..Default::default()
/// }));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageRef {
    /// Reference to component message
    ///
    /// Points to a reusable message definition in the components section.
    /// Format: "#/components/messages/{messageName}"
    Reference {
        /// $ref path
        #[serde(rename = "$ref")]
        reference: String,
    },
    /// Inline message definition
    ///
    /// Embeds the message definition directly rather than referencing a component
    Inline(Box<Message>),
}

/// Message definition
///
/// Represents a message that can be sent or received through a channel.
/// Messages describe the structure, content type, and documentation for data
/// exchanged in asynchronous communication.
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::{Message, Schema, SchemaObject};
/// use indexmap::IndexMap;
///
/// let message = Message {
///     name: Some("ChatMessage".to_string()),
///     title: Some("Chat Message".to_string()),
///     summary: Some("A message in a chat room".to_string()),
///     description: Some("Sent when a user posts a message".to_string()),
///     content_type: Some("application/json".to_string()),
///     payload: Some(Schema::Object(Box::new(SchemaObject {
///         schema_type: Some(serde_json::json!("object")),
///         properties: None,
///         required: None,
///         description: Some("Chat message payload".to_string()),
///         title: None,
///         enum_values: None,
///         const_value: None,
///         items: None,
///         additional_properties: None,
///         one_of: None,
///         any_of: None,
///         all_of: None,
///         additional: IndexMap::new(),
///     }))),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Message {
    /// Message name
    ///
    /// A machine-readable identifier for the message (e.g., "ChatMessage", "user.join")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Message title
    ///
    /// A human-readable title for the message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Message summary
    ///
    /// A short summary of what the message is for
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,

    /// Message description
    ///
    /// A detailed description of the message's purpose and usage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Content type (e.g., "application/json")
    ///
    /// The MIME type of the message payload. Common values:
    /// - "application/json" (default for text messages)
    /// - "application/octet-stream" (binary data)
    /// - "application/x-protobuf" (Protocol Buffers)
    /// - "application/x-msgpack" (MessagePack)
    #[serde(rename = "contentType", skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,

    /// Message payload schema
    ///
    /// JSON Schema defining the structure of the message payload
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<Schema>,

    /// Protocol specific bindings.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub bindings: Option<MessageBindings>,
}

/// Protocol specific message bindings
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct MessageBindings {
    /// Mqtt protocol specific message bindings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mqtt: Option<MqttMessageBindings>,
}

/// Mqtt response topic
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum MqttResponseTopic {
    /// Topic Uri
    Uri(String),
    /// Schema for the response topic
    Schema(Schema),
}

/// Mqtt message bindings
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct MqttMessageBindings {
    /// Either: 0 (zero): Indicates that the payload is unspecified bytes, or 1: Indicates that the payload is UTF-8 encoded character data.
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "payloadFormatIndicator"
    )]
    pub payload_format_indicator: Option<u8>,

    /// Correlation Data is used by the sender of the request message to identify which request the response message is for when it is received.
    #[serde(skip_serializing_if = "Option::is_none", rename = "correlationData")]
    pub correlation_data: Option<Schema>,

    /// String describing the content type of the message payload. This should not conflict with the contentType field of the associated AsyncAPI Message object.
    #[serde(skip_serializing_if = "Option::is_none", rename = "contentType")]
    pub content_type: Option<String>,

    /// The topic (channel URI) for a response message.
    #[serde(skip_serializing_if = "Option::is_none", rename = "responseTopic")]
    pub response_topic: Option<MqttResponseTopic>,

    /// The version of this binding. If omitted, "latest" MUST be assumed.
    #[serde(skip_serializing_if = "Option::is_none", rename = "bindingVersion")]
    pub binding_version: Option<String>,
}

/// Operation (send or receive)
///
/// Defines an action that can be performed on a channel. Operations describe
/// whether an application sends or receives messages through a specific channel.
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::{Operation, OperationAction, ChannelRef};
///
/// let operation = Operation {
///     action: OperationAction::Send,
///     channel: ChannelRef {
///         reference: "#/channels/chat".to_string(),
///     },
///     messages: None,
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Operation {
    /// Operation action (send or receive)
    ///
    /// Specifies whether the application sends or receives messages
    pub action: OperationAction,

    /// Channel reference
    ///
    /// Points to the channel where this operation takes place
    pub channel: ChannelRef,

    /// Messages for this operation
    ///
    /// Optional list of messages that can be used with this operation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub messages: Option<Vec<MessageRef>>,

    /// Protocol specific bindings
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub bindings: Option<OperationBindings>,
}

/// Protocol specific operation bindings
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct OperationBindings {
    /// Mqtt specific operation bindings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mqtt: Option<MqttOperationBindings>,
}

/// Mqtt operation bindings
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct MqttOperationBindings {
    /// Defines the Quality of Service (QoS) levels for the message flow between client and server.
    /// Its value MUST be either 0 (At most once delivery), 1 (At least once delivery), or 2 (Exactly once delivery).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qos: Option<u8>,

    /// Whether the broker should retain the message or not.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retain: Option<bool>,

    /// Interval in seconds or a Schema Object containing the definition of the lifetime of the message.
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "messageExpiryInterval"
    )]
    pub message_expiry_interval: Option<MqttBindingNumValue>,

    /// The version of this binding. If omitted, "latest" MUST be assumed.
    #[serde(skip_serializing_if = "Option::is_none", rename = "bindingVersion")]
    pub binding_version: Option<String>,
}

/// Operation action type
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum OperationAction {
    /// Send message
    #[default]
    Send,
    /// Receive message
    Receive,
}

/// Reference to a channel
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ChannelRef {
    /// $ref path
    #[serde(rename = "$ref")]
    pub reference: String,
}

/// Reusable components
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Components {
    /// Message definitions
    #[serde(skip_serializing_if = "Option::is_none")]
    pub messages: Option<IndexMap<String, Message>>,

    /// Schema definitions
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schemas: Option<IndexMap<String, Schema>>,
}

/// JSON Schema object
///
/// Flexible representation that can hold any valid JSON Schema. This type supports
/// both schema references (using `$ref`) and complete inline schema definitions.
///
/// Schemas define the structure and validation rules for message payloads,
/// following the JSON Schema specification.
///
/// # Example
///
/// ## Reference Schema
///
/// ```rust
/// use asyncapi_rust_models::Schema;
///
/// let schema = Schema::Reference {
///     reference: "#/components/schemas/ChatMessage".to_string(),
/// };
/// ```
///
/// ## Object Schema
///
/// ```rust
/// use asyncapi_rust_models::{Schema, SchemaObject};
/// use indexmap::IndexMap;
///
/// let schema = Schema::Object(Box::new(SchemaObject {
///     schema_type: Some(serde_json::json!("object")),
///     properties: None,
///     required: Some(vec!["username".to_string(), "room".to_string()]),
///     description: Some("A chat message".to_string()),
///     title: Some("ChatMessage".to_string()),
///     enum_values: None,
///     const_value: None,
///     items: None,
///     additional_properties: None,
///     one_of: None,
///     any_of: None,
///     all_of: None,
///     additional: IndexMap::new(),
/// }));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Schema {
    /// Reference to another schema ($ref)
    ///
    /// Points to a reusable schema definition in the components section.
    /// Format: "#/components/schemas/{schemaName}"
    Reference {
        /// $ref path
        #[serde(rename = "$ref")]
        reference: String,
    },
    /// Full schema object (boxed to reduce enum size)
    ///
    /// Contains a complete JSON Schema definition with all properties inline
    Object(Box<SchemaObject>),
    /// Catch-all for valid JSON Schemas that don't match the above variants
    ///
    /// Handles minimal schemas like `{}`, `{"title": "..."}`, or boolean schemas
    /// (`true`/`false`) that are valid per the JSON Schema spec but carry no
    /// structural information. `schemars` emits these for open-ended types such
    /// as `serde_json::Value`.
    Any(serde_json::Value),
}

/// Schema object with all JSON Schema properties
///
/// Complete representation of a JSON Schema with support for all standard properties.
/// This struct provides fine-grained control over schema definitions for message payloads.
///
/// # Example
///
/// ```rust
/// use asyncapi_rust_models::{Schema, SchemaObject};
/// use indexmap::IndexMap;
///
/// // String property schema
/// let username_schema = Schema::Object(Box::new(SchemaObject {
///     schema_type: Some(serde_json::json!("string")),
///     properties: None,
///     required: None,
///     description: Some("User's display name".to_string()),
///     title: None,
///     enum_values: None,
///     const_value: None,
///     items: None,
///     additional_properties: None,
///     one_of: None,
///     any_of: None,
///     all_of: None,
///     additional: IndexMap::new(),
/// }));
///
/// // Object schema with properties
/// let mut properties = IndexMap::new();
/// properties.insert("username".to_string(), Box::new(username_schema));
///
/// let message_schema = SchemaObject {
///     schema_type: Some(serde_json::json!("object")),
///     properties: Some(properties),
///     required: Some(vec!["username".to_string()]),
///     description: Some("A chat message".to_string()),
///     title: Some("ChatMessage".to_string()),
///     enum_values: None,
///     const_value: None,
///     items: None,
///     additional_properties: None,
///     one_of: None,
///     any_of: None,
///     all_of: None,
///     additional: IndexMap::new(),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaObject {
    /// Schema type
    ///
    /// The JSON Schema type: "object", "array", "string", "number", "integer", "boolean", "null"
    /// Can also be an array of types for schemas that allow multiple types (e.g., ["string", "null"])
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub schema_type: Option<serde_json::Value>,

    /// Properties (for object type)
    ///
    /// Map of property names to their schemas when schema_type is "object"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<IndexMap<String, Box<Schema>>>,

    /// Required properties
    ///
    /// List of property names that must be present (for object types)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,

    /// Description
    ///
    /// Human-readable description of what this schema represents
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Title
    ///
    /// A short title for the schema
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Enum values
    ///
    /// List of allowed values (for enum types)
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<serde_json::Value>>,

    /// Const value
    ///
    /// A single constant value that this schema must match
    #[serde(rename = "const", skip_serializing_if = "Option::is_none")]
    pub const_value: Option<serde_json::Value>,

    /// Items schema (for array type)
    ///
    /// Schema for array elements when schema_type is "array"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<Box<Schema>>,

    /// Additional properties
    ///
    /// Schema for additional properties not explicitly defined (for object types)
    #[serde(
        rename = "additionalProperties",
        skip_serializing_if = "Option::is_none"
    )]
    pub additional_properties: Option<Box<Schema>>,

    /// OneOf schemas
    ///
    /// Value must match exactly one of these schemas (XOR logic)
    #[serde(rename = "oneOf", skip_serializing_if = "Option::is_none")]
    pub one_of: Option<Vec<Schema>>,

    /// AnyOf schemas
    ///
    /// Value must match at least one of these schemas (OR logic)
    #[serde(rename = "anyOf", skip_serializing_if = "Option::is_none")]
    pub any_of: Option<Vec<Schema>>,

    /// AllOf schemas
    ///
    /// Value must match all of these schemas (AND logic)
    #[serde(rename = "allOf", skip_serializing_if = "Option::is_none")]
    pub all_of: Option<Vec<Schema>>,

    /// Additional fields that may be present in the schema
    ///
    /// Captures any additional JSON Schema properties not explicitly defined above
    #[serde(flatten)]
    pub additional: IndexMap<String, serde_json::Value>,
}

impl Default for AsyncApiSpec {
    fn default() -> Self {
        Self {
            asyncapi: "3.0.0".to_string(),
            info: Info {
                title: "API".to_string(),
                version: "1.0.0".to_string(),
                description: None,
            },
            servers: None,
            channels: None,
            operations: None,
            components: None,
        }
    }
}

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

    #[test]
    fn test_spec_serialization() {
        let spec = AsyncApiSpec::default();
        let json = serde_json::to_string(&spec).unwrap();
        assert!(json.contains("asyncapi"));
        assert!(json.contains("3.0.0"));
    }

    #[test]
    fn test_spec_deserialization() {
        let json = r#"{
            "asyncapi": "3.0.0",
            "info": {
                "title": "Test API",
                "version": "1.0.0"
            }
        }"#;
        let spec: AsyncApiSpec = serde_json::from_str(json).unwrap();
        assert_eq!(spec.asyncapi, "3.0.0");
        assert_eq!(spec.info.title, "Test API");
    }
}