mzrs-sdk 0.1.20

High-level Rust SDK for Mezon platform
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
//! High-level Mezon client with builder pattern.
//!
//! [`MzrsClient`] wraps [`ClientRuntime`] and provides ergonomic methods
//! for authentication, realtime connectivity, and message operations.

use std::sync::Arc;
use std::time::Duration;

use serde_json::Value;
use tokio::sync::broadcast;

use mzrs_core::{ClientConfigBuilder, ClientRuntime, Event, Session};
use mzrs_proto::{api, realtime as rt};

use crate::error::SdkError;
use crate::handles::{ChannelHandle, ClanHandle};
use crate::types::ChannelType;
use crate::upload::AttachmentSource;

/// Default timeout for request/response round-trips.
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

// ── Request types ───────────────────────────────────────────────────

/// Request payload for joining a chat channel.
#[derive(Clone, Debug)]
pub struct JoinChatRequest {
    /// The clan that owns the channel.
    pub clan_id: String,
    /// The channel to join.
    pub channel_id: String,
    /// Channel type (see [`ChannelType`](crate::ChannelType)).
    pub channel_type: i32,
    /// Whether the channel is public.
    pub is_public: bool,
}

/// Request payload for leaving a chat channel.
#[derive(Clone, Debug)]
pub struct LeaveChatRequest {
    /// The clan that owns the channel.
    pub clan_id: String,
    /// The channel to leave.
    pub channel_id: String,
    /// Channel type.
    pub channel_type: i32,
    /// Whether the channel is public.
    pub is_public: bool,
}

/// Request payload for sending a message.
#[derive(Clone, Debug)]
pub struct SendMessageRequest {
    /// The clan that owns the channel.
    pub clan_id: String,
    /// The target channel.
    pub channel_id: String,
    /// Stream mode (see [`StreamMode`](crate::StreamMode)).
    pub mode: i32,
    /// Whether the channel is public.
    pub is_public: bool,
    /// JSON content of the message.
    pub content: Value,
    /// Mentions list.
    pub mentions: Vec<api::MessageMention>,
    /// Attachments list.
    pub attachments: Vec<api::MessageAttachment>,
    /// Message references (replies).
    pub references: Vec<api::MessageRef>,
    /// Whether this is an anonymous message.
    pub anonymous_message: bool,
    /// Whether this message mentions everyone.
    pub mention_everyone: bool,
    /// Optional avatar URL override.
    pub avatar: Option<String>,
    /// Message type code (see [`MessageCode`](crate::MessageCode)).
    pub code: i32,
    /// Optional topic ID for threaded messages.
    pub topic_id: Option<String>,
    /// Optional custom message ID.
    pub id: Option<String>,
}

/// Request payload for updating a message.
#[derive(Clone, Debug)]
pub struct UpdateMessageRequest {
    /// The clan that owns the channel.
    pub clan_id: String,
    /// The channel containing the message.
    pub channel_id: String,
    /// The message to update.
    pub message_id: String,
    /// Stream mode.
    pub mode: i32,
    /// Whether the channel is public.
    pub is_public: bool,
    /// New JSON content.
    pub content: Value,
    /// Mentions list.
    pub mentions: Vec<api::MessageMention>,
    /// Attachments list.
    pub attachments: Vec<api::MessageAttachment>,
    /// Whether to hide the "edited" indicator.
    pub hide_editted: bool,
    /// Optional topic ID.
    pub topic_id: Option<String>,
    /// Whether this is a topic message update.
    pub is_update_msg_topic: bool,
}

/// Request payload for deleting a message.
#[derive(Clone, Debug)]
pub struct DeleteMessageRequest {
    /// The clan that owns the channel.
    pub clan_id: String,
    /// The channel containing the message.
    pub channel_id: String,
    /// The message to delete.
    pub message_id: String,
    /// Stream mode.
    pub mode: i32,
    /// Whether the channel is public.
    pub is_public: bool,
    /// Whether the message has an attachment.
    pub has_attachment: bool,
    /// Optional topic ID.
    pub topic_id: Option<String>,
    /// Protobuf-encoded mentions.
    pub mentions: Vec<u8>,
    /// Protobuf-encoded references.
    pub references: Vec<u8>,
}

/// Request payload for reacting to a message.
#[derive(Clone, Debug)]
pub struct ReactMessageRequest {
    /// Optional reaction ID.
    pub id: Option<String>,
    /// The clan that owns the channel.
    pub clan_id: String,
    /// The channel containing the message.
    pub channel_id: String,
    /// Stream mode.
    pub mode: i32,
    /// Whether the channel is public.
    pub is_public: bool,
    /// The message to react to.
    pub message_id: String,
    /// The emoji ID.
    pub emoji_id: String,
    /// The emoji character or shortcode.
    pub emoji: String,
    /// Reaction count.
    pub count: i32,
    /// The sender of the original message.
    pub message_sender_id: String,
    /// Optional sender ID for the reaction.
    pub sender_id: Option<String>,
    /// Optional sender display name.
    pub sender_name: Option<String>,
    /// Optional sender avatar URL.
    pub sender_avatar: Option<String>,
    /// Whether this is a removal (true = remove reaction).
    pub action_delete: bool,
    /// Optional topic ID.
    pub topic_id: Option<String>,
    /// Optional recent emoji ID.
    pub emoji_recent_id: Option<String>,
}

// ── MzrsClientBuilder ───────────────────────────────────────────────

/// Builder for [`MzrsClient`] with configuration delegation to
/// [`ClientConfigBuilder`].
#[derive(Clone)]
pub struct MzrsClientBuilder {
    config_builder: ClientConfigBuilder,
    request_timeout: Duration,
}

impl Default for MzrsClientBuilder {
    fn default() -> Self {
        Self {
            config_builder: ClientConfigBuilder::default(),
            request_timeout: DEFAULT_REQUEST_TIMEOUT,
        }
    }
}

impl MzrsClientBuilder {
    /// Create a new builder with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the bot application ID (required).
    pub fn bot_id(mut self, value: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.bot_id(value);
        self
    }

    /// Set the authentication token (required).
    pub fn token(mut self, value: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.token(value);
        self
    }

    /// Set the gateway host.
    pub fn host(mut self, value: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.host(value);
        self
    }

    /// Set the gateway port.
    pub fn port(mut self, value: u16) -> Self {
        self.config_builder = self.config_builder.port(value);
        self
    }

    /// Enable or disable TLS.
    pub fn use_ssl(mut self, value: bool) -> Self {
        self.config_builder = self.config_builder.use_ssl(value);
        self
    }

    /// Set the WebSocket path.
    pub fn ws_path(mut self, value: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.ws_path(value);
        self
    }

    /// Enable or disable automatic reconnection.
    pub fn auto_reconnect(mut self, value: bool) -> Self {
        self.config_builder = self.config_builder.auto_reconnect(value);
        self
    }

    /// Set the maximum number of reconnection attempts.
    pub fn max_reconnect_attempts(mut self, value: Option<u32>) -> Self {
        self.config_builder = self.config_builder.max_reconnect_attempts(value);
        self
    }

    /// Set the initial backoff between reconnect attempts.
    pub fn reconnect_initial_backoff(mut self, value: Duration) -> Self {
        self.config_builder = self.config_builder.reconnect_initial_backoff(value);
        self
    }

    /// Set the maximum backoff between reconnect attempts.
    pub fn reconnect_max_backoff(mut self, value: Duration) -> Self {
        self.config_builder = self.config_builder.reconnect_max_backoff(value);
        self
    }

    /// Set the heartbeat ping interval.
    pub fn heartbeat_interval(mut self, value: Duration) -> Self {
        self.config_builder = self.config_builder.heartbeat_interval(value);
        self
    }

    /// Set the heartbeat pong timeout.
    pub fn heartbeat_timeout(mut self, value: Duration) -> Self {
        self.config_builder = self.config_builder.heartbeat_timeout(value);
        self
    }

    /// Set the HTTP request timeout.
    pub fn timeout(mut self, value: Duration) -> Self {
        self.config_builder = self.config_builder.timeout(value);
        self
    }

    /// Set the timeout for request/response round-trips (default 10s).
    pub fn request_timeout(mut self, value: Duration) -> Self {
        self.request_timeout = value;
        self
    }

    /// Validate configuration and build the [`MzrsClient`].
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::Core`] if the configuration is invalid or the
    /// runtime cannot be created.
    pub fn build(self) -> Result<MzrsClient, SdkError> {
        let config = self.config_builder.build()?;
        let runtime = ClientRuntime::new(config)?;

        Ok(MzrsClient {
            runtime: Arc::new(runtime),
            request_timeout: self.request_timeout,
        })
    }
}

// ── MzrsClient ──────────────────────────────────────────────────────

/// High-level client for the Mezon platform.
///
/// Wraps [`ClientRuntime`] with ergonomic APIs for authentication,
/// messaging, and event subscription. Cheaply cloneable (reference-counted).
///
/// # Example
///
/// ```rust,ignore
/// let client = MzrsClient::builder()
///     .bot_id("my-bot")
///     .token("secret-token")
///     .build()?;
///
/// client.login().await?;
/// client.connect().await?;
///
/// let mut events = client.subscribe();
/// while let Ok(event) = events.recv().await {
///     // handle events
/// }
/// ```
#[derive(Clone)]
pub struct MzrsClient {
    runtime: Arc<ClientRuntime>,
    request_timeout: Duration,
}

impl MzrsClient {
    /// Create a new [`MzrsClientBuilder`].
    pub fn builder() -> MzrsClientBuilder {
        MzrsClientBuilder::default()
    }

    /// Return a reference to the underlying [`ClientRuntime`].
    pub fn runtime(&self) -> &ClientRuntime {
        self.runtime.as_ref()
    }

    /// Subscribe to the event broadcast channel.
    ///
    /// Each call returns an independent receiver. Slow receivers that fall
    /// behind will lose older events.
    pub fn subscribe(&self) -> broadcast::Receiver<Event> {
        self.runtime.subscribe()
    }

    // ── Authentication ──────────────────────────────────────────────

    /// Authenticate with the Mezon API using the configured credentials.
    ///
    /// On success the session is stored internally and returned.
    #[tracing::instrument(skip(self))]
    pub async fn login(&self) -> Result<Session, SdkError> {
        self.runtime.login().await.map_err(SdkError::from)
    }

    /// Return the current session, if any.
    pub async fn session(&self) -> Option<Session> {
        self.runtime.session().await
    }

    /// Manually set the session (e.g. when restoring from cache).
    pub async fn set_session(&self, session: Session) {
        self.runtime.set_session(session).await;
    }

    // ── Realtime connectivity ───────────────────────────────────────

    /// Connect to the realtime WebSocket gateway.
    #[tracing::instrument(skip(self))]
    pub async fn connect(&self) -> Result<(), SdkError> {
        self.runtime
            .connect_realtime()
            .await
            .map_err(SdkError::from)
    }

    /// Connect to the realtime gateway with exponential backoff retries.
    #[tracing::instrument(skip(self))]
    pub async fn connect_with_retry(&self) -> Result<(), SdkError> {
        self.runtime
            .connect_realtime_with_retry()
            .await
            .map_err(SdkError::from)
    }

    // ── Handles ─────────────────────────────────────────────────────

    /// Create a [`ClanHandle`] scoped to the given clan.
    pub fn clan(&self, clan_id: impl Into<String>) -> ClanHandle {
        ClanHandle::new(self.clone(), clan_id.into())
    }

    /// Create a [`ChannelHandle`] scoped to a specific channel.
    pub fn channel(
        &self,
        clan_id: impl Into<String>,
        channel_id: impl Into<String>,
    ) -> ChannelHandle {
        ChannelHandle::new(self.clone(), clan_id.into(), channel_id.into())
    }

    // ── Low-level envelope access ───────────────────────────────────

    /// Send a raw realtime envelope.
    #[tracing::instrument(skip(self, envelope))]
    pub async fn send_envelope(&self, envelope: &rt::Envelope) -> Result<(), SdkError> {
        self.runtime
            .send_envelope(envelope)
            .await
            .map_err(SdkError::from)
    }

    /// Send an envelope and wait for the correlated response.
    #[tracing::instrument(skip(self, envelope))]
    pub async fn request_envelope(&self, envelope: rt::Envelope) -> Result<rt::Envelope, SdkError> {
        self.runtime
            .request(envelope, self.request_timeout)
            .await
            .map_err(SdkError::from)
    }

    // ── REST API ────────────────────────────────────────────────────

    /// List clans the authenticated bot belongs to.
    #[tracing::instrument(skip(self))]
    pub async fn list_clans(&self) -> Result<Vec<api::ClanDesc>, SdkError> {
        self.runtime.list_clans().await.map_err(SdkError::from)
    }

    /// Create a channel descriptor via REST.
    ///
    /// For DM creation, see [`Self::create_dm`].
    #[tracing::instrument(skip(self, request))]
    pub async fn create_channel(
        &self,
        request: api::CreateChannelDescRequest,
    ) -> Result<api::ChannelDescription, SdkError> {
        self.runtime
            .create_channel(request)
            .await
            .map_err(SdkError::from)
    }

    /// Create a direct-message channel with one peer user.
    ///
    /// This mirrors the JS SDK `createDM(peerId)` flow:
    /// `type = DM`, `channel_private = 1`, `user_ids = [peerId]`.
    #[tracing::instrument(skip(self), fields(peer_id = peer_id))]
    pub async fn create_dm(&self, peer_id: &str) -> Result<api::ChannelDescription, SdkError> {
        let peer_id = parse_id(peer_id, "peer_id")?;
        self.create_channel(api::CreateChannelDescRequest {
            r#type: ChannelType::Dm as i32,
            channel_private: 1,
            user_ids: vec![peer_id],
            ..Default::default()
        })
        .await
    }

    /// Update a channel descriptor via REST.
    ///
    /// Use this to update label/topic/avatar and related metadata.
    #[tracing::instrument(skip(self, request))]
    pub async fn update_channel_desc(
        &self,
        request: api::UpdateChannelDescRequest,
    ) -> Result<(), SdkError> {
        self.runtime
            .update_channel_desc(request)
            .await
            .map_err(SdkError::from)
    }

    /// Convenience helper to update only a channel avatar.
    #[tracing::instrument(skip(self, channel_avatar))]
    pub async fn update_channel_avatar(
        &self,
        clan_id: &str,
        channel_id: &str,
        channel_avatar: Option<String>,
    ) -> Result<(), SdkError> {
        self.update_channel_desc(api::UpdateChannelDescRequest {
            clan_id: parse_id(clan_id, "clan_id")?,
            channel_id: parse_id(channel_id, "channel_id")?,
            channel_avatar,
            ..Default::default()
        })
        .await
    }

    /// Update current user's profile inside a clan (nickname/avatar).
    #[tracing::instrument(skip(self, request))]
    pub async fn update_user_profile_by_clan(
        &self,
        request: api::UpdateClanProfileRequest,
    ) -> Result<(), SdkError> {
        self.runtime
            .update_user_profile_by_clan(request)
            .await
            .map_err(SdkError::from)
    }

    /// Convenience helper to update nickname/avatar in a clan profile.
    #[tracing::instrument(skip(self, nick_name, avatar))]
    pub async fn update_clan_profile(
        &self,
        clan_id: &str,
        nick_name: Option<String>,
        avatar: Option<String>,
    ) -> Result<(), SdkError> {
        self.update_user_profile_by_clan(api::UpdateClanProfileRequest {
            clan_id: parse_id(clan_id, "clan_id")?,
            nick_name,
            avatar,
        })
        .await
    }

    /// Convenience helper to update only avatar in current user's clan profile.
    #[tracing::instrument(skip(self, avatar))]
    pub async fn update_clan_profile_avatar(
        &self,
        clan_id: &str,
        avatar: Option<String>,
    ) -> Result<(), SdkError> {
        self.update_clan_profile(clan_id, None, avatar).await
    }

    // ── Clan chat ───────────────────────────────────────────────────

    /// Join the chat stream for a clan.
    #[tracing::instrument(skip(self))]
    pub async fn join_clan_chat(&self, clan_id: &str) -> Result<rt::ClanJoin, SdkError> {
        let response = self
            .request_envelope(rt::Envelope {
                clan_join: Some(rt::ClanJoin {
                    clan_id: parse_id(clan_id, "clan_id")?,
                }),
                ..Default::default()
            })
            .await?;

        map_realtime_error(&response)?;

        response.clan_join.ok_or_else(|| {
            SdkError::Core(mzrs_core::CoreError::Decode(
                "missing clan_join in response".to_string(),
            ))
        })
    }

    /// Join a specific chat channel.
    #[tracing::instrument(skip(self, request))]
    pub async fn join_chat(&self, request: JoinChatRequest) -> Result<rt::Channel, SdkError> {
        let response = self
            .request_envelope(rt::Envelope {
                channel_join: Some(rt::ChannelJoin {
                    clan_id: parse_id(&request.clan_id, "clan_id")?,
                    channel_id: parse_id(&request.channel_id, "channel_id")?,
                    channel_type: request.channel_type,
                    is_public: request.is_public,
                }),
                ..Default::default()
            })
            .await?;

        map_realtime_error(&response)?;

        response.channel.ok_or_else(|| {
            SdkError::Core(mzrs_core::CoreError::Decode(
                "missing channel in response".to_string(),
            ))
        })
    }

    /// Leave a chat channel.
    #[tracing::instrument(skip(self, request))]
    pub async fn leave_chat(&self, request: LeaveChatRequest) -> Result<(), SdkError> {
        let response = self
            .request_envelope(rt::Envelope {
                channel_leave: Some(rt::ChannelLeave {
                    clan_id: parse_id(&request.clan_id, "clan_id")?,
                    channel_id: parse_id(&request.channel_id, "channel_id")?,
                    channel_type: request.channel_type,
                    is_public: request.is_public,
                }),
                ..Default::default()
            })
            .await?;

        map_realtime_error(&response)?;
        Ok(())
    }

    /// Send a message to a channel.
    #[tracing::instrument(skip(self, request))]
    pub async fn send_message(
        &self,
        request: SendMessageRequest,
    ) -> Result<rt::ChannelMessageAck, SdkError> {
        let content = serde_json::to_string(&request.content)
            .map_err(|err| SdkError::Core(mzrs_core::CoreError::Encode(err.to_string())))?;

        let response = self
            .request_envelope(rt::Envelope {
                channel_message_send: Some(rt::ChannelMessageSend {
                    clan_id: parse_id(&request.clan_id, "clan_id")?,
                    channel_id: parse_id(&request.channel_id, "channel_id")?,
                    content,
                    mentions: request.mentions,
                    attachments: request.attachments,
                    references: request.references,
                    mode: request.mode,
                    anonymous_message: request.anonymous_message,
                    mention_everyone: request.mention_everyone,
                    avatar: request.avatar.unwrap_or_default(),
                    is_public: request.is_public,
                    code: request.code,
                    topic_id: parse_optional_id(request.topic_id.as_deref(), "topic_id")?,
                    id: parse_optional_id(request.id.as_deref(), "id")?,
                }),
                ..Default::default()
            })
            .await?;

        map_realtime_error(&response)?;

        response.channel_message_ack.ok_or_else(|| {
            SdkError::Core(mzrs_core::CoreError::Decode(
                "missing channel_message_ack in response".to_string(),
            ))
        })
    }

    /// Update an existing message.
    #[tracing::instrument(skip(self, request))]
    pub async fn update_message(
        &self,
        request: UpdateMessageRequest,
    ) -> Result<rt::ChannelMessageAck, SdkError> {
        let content = serde_json::to_string(&request.content)
            .map_err(|err| SdkError::Core(mzrs_core::CoreError::Encode(err.to_string())))?;

        let has_topic_update = request.is_update_msg_topic || request.topic_id.is_some();

        let response = self
            .request_envelope(rt::Envelope {
                channel_message_update: Some(rt::ChannelMessageUpdate {
                    clan_id: parse_id(&request.clan_id, "clan_id")?,
                    channel_id: parse_id(&request.channel_id, "channel_id")?,
                    message_id: parse_id(&request.message_id, "message_id")?,
                    content,
                    mentions: request.mentions,
                    attachments: request.attachments,
                    mode: request.mode,
                    is_public: request.is_public,
                    hide_editted: request.hide_editted,
                    topic_id: parse_optional_id(request.topic_id.as_deref(), "topic_id")?,
                    is_update_msg_topic: has_topic_update,
                }),
                ..Default::default()
            })
            .await?;

        map_realtime_error(&response)?;

        response.channel_message_ack.ok_or_else(|| {
            SdkError::Core(mzrs_core::CoreError::Decode(
                "missing channel_message_ack in response".to_string(),
            ))
        })
    }

    /// Delete a message.
    #[tracing::instrument(skip(self, request))]
    pub async fn delete_message(
        &self,
        request: DeleteMessageRequest,
    ) -> Result<rt::ChannelMessageAck, SdkError> {
        let response = self
            .request_envelope(rt::Envelope {
                channel_message_remove: Some(rt::ChannelMessageRemove {
                    clan_id: parse_id(&request.clan_id, "clan_id")?,
                    channel_id: parse_id(&request.channel_id, "channel_id")?,
                    message_id: parse_id(&request.message_id, "message_id")?,
                    mode: request.mode,
                    is_public: request.is_public,
                    has_attachment: request.has_attachment,
                    topic_id: parse_optional_id(request.topic_id.as_deref(), "topic_id")?,
                    mentions: request.mentions,
                    references: request.references,
                }),
                ..Default::default()
            })
            .await?;

        map_realtime_error(&response)?;

        response.channel_message_ack.ok_or_else(|| {
            SdkError::Core(mzrs_core::CoreError::Decode(
                "missing channel_message_ack in response".to_string(),
            ))
        })
    }

    /// Add or remove a reaction on a message.
    #[tracing::instrument(skip(self, request))]
    pub async fn react_message(
        &self,
        request: ReactMessageRequest,
    ) -> Result<api::MessageReaction, SdkError> {
        let response = self
            .request_envelope(rt::Envelope {
                message_reaction_event: Some(api::MessageReaction {
                    id: parse_optional_id(request.id.as_deref(), "id")?,
                    emoji_id: parse_id(&request.emoji_id, "emoji_id")?,
                    emoji: request.emoji,
                    sender_id: parse_optional_id(request.sender_id.as_deref(), "sender_id")?,
                    sender_name: request.sender_name.unwrap_or_default(),
                    sender_avatar: request.sender_avatar.unwrap_or_default(),
                    action: request.action_delete,
                    count: request.count,
                    channel_id: parse_id(&request.channel_id, "channel_id")?,
                    message_id: parse_id(&request.message_id, "message_id")?,
                    clan_id: parse_id(&request.clan_id, "clan_id")?,
                    mode: request.mode,
                    message_sender_id: parse_id(&request.message_sender_id, "message_sender_id")?,
                    is_public: request.is_public,
                    topic_id: parse_optional_id(request.topic_id.as_deref(), "topic_id")?,
                    emoji_recent_id: parse_optional_id(
                        request.emoji_recent_id.as_deref(),
                        "emoji_recent_id",
                    )?,
                }),
                ..Default::default()
            })
            .await?;

        map_realtime_error(&response)?;

        response.message_reaction_event.ok_or_else(|| {
            SdkError::Core(mzrs_core::CoreError::Decode(
                "missing message_reaction_event in response".to_string(),
            ))
        })
    }

    // ── File upload ─────────────────────────────────────────────────

    /// Direct attachment upload is not supported by the current Mezon bot API.
    ///
    /// This method is kept only for API compatibility and always returns
    /// [`SdkError::Core`] wrapping [`mzrs_core::CoreError::Unsupported`].
    #[deprecated(
        note = "Mezon bot attachment upload is not supported; attach externally hosted URLs instead"
    )]
    #[tracing::instrument(skip(self, _source, _filename, _filetype))]
    pub async fn upload_attachment(
        &self,
        _source: impl Into<AttachmentSource>,
        _filename: impl Into<String>,
        _filetype: impl Into<String>,
    ) -> Result<api::MessageAttachment, SdkError> {
        Err(SdkError::Core(mzrs_core::CoreError::Unsupported(
            "Mezon does not support attachment upload for bots".to_string(),
        )))
    }

    // ── Shutdown ────────────────────────────────────────────────────

    /// Gracefully shut down the client and release all resources.
    #[tracing::instrument(skip(self))]
    pub async fn close(&self) -> Result<(), SdkError> {
        self.runtime.close().await.map_err(SdkError::from)
    }
}

// ── Helpers ─────────────────────────────────────────────────────────

/// Check the envelope for a realtime error and convert it to an `SdkError`.
fn map_realtime_error(envelope: &rt::Envelope) -> Result<(), SdkError> {
    if let Some(ref err) = envelope.error {
        return Err(SdkError::Core(mzrs_core::CoreError::Decode(format!(
            "realtime error {}: {}",
            err.code, err.message
        ))));
    }
    Ok(())
}

/// Parse a string ID to `i64`.
fn parse_id(value: &str, field: &str) -> Result<i64, SdkError> {
    value.parse::<i64>().map_err(|_| {
        SdkError::Validation(format!(
            "invalid {field}, expected int64 string but got '{value}'"
        ))
    })
}

/// Parse an optional string ID to `i64`, defaulting to `0`.
fn parse_optional_id(value: Option<&str>, field: &str) -> Result<i64, SdkError> {
    match value {
        Some(raw) if !raw.trim().is_empty() => parse_id(raw, field),
        _ => Ok(0),
    }
}