rustpbx 0.3.19

A SIP PBX implementation in Rust
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
//! HTTP handlers for the Voicemail Pro web UI and REST API.
//!
//! ## URL map
//!
//! | Method | Path | Handler |
//! |--------|------|---------|
//! | GET    | /console/voicemail                                    | `ui_list_mailboxes`    |
//! | GET    | /console/voicemail/:extension                         | `ui_mailbox_messages`  |
//! | POST   | /console/voicemail/mailboxes                          | `form_create_mailbox`  |
//! | POST   | /console/voicemail/mailboxes/:ext/delete              | `form_delete_mailbox`  |
//! | POST   | /console/voicemail/mailboxes/:ext/reset-pin           | `form_reset_pin`       |
//! | POST   | /console/voicemail/messages/:id/delete                | `form_delete_message`  |
//! | POST   | /console/voicemail/messages/:id/read                  | `form_mark_read`       |
//! | GET    | /api/voicemail/messages/:id/audio                     | `api_audio`            |
//! | GET    | /api/voicemail/:extension/messages                    | `api_list_messages`    |
//! | GET    | /api/voicemail/prompts/:name/audio                    | `api_prompt_audio`     |
//! | POST   | /api/voicemail/prompts/:name/upload                   | `api_prompt_upload`    |
//! | POST   | /api/voicemail/prompts/:name/from-url                 | `api_prompt_from_url`  |

use axum::{
    Json,
    extract::{Multipart, Path, Query, State},
    http::{HeaderMap, StatusCode, header},
    response::{IntoResponse, Redirect, Response},
};
use sea_orm::{
    ActiveModelTrait, ColumnTrait, EntityTrait, Order, PaginatorTrait, QueryFilter, QueryOrder, Set,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::sync::Arc;
use tracing::warn;
use uuid::Uuid;

use crate::app::AppState;
use crate::addons::voicemail::mailbox_service::MailboxService;
use crate::addons::voicemail::models::{
    mailbox::{
        ActiveModel as MailboxActiveModel, Column as MailboxColumn, Entity as MailboxEntity,
    },
    message::{
        ActiveModel as MessageActiveModel, Column as MessageColumn, Entity as MessageEntity,
        Model as Message,
    },
};
use crate::addons::voicemail::settings::{FileConfig, SettingsForm};
use crate::addons::voicemail::storage::VoicemailStorage;

// ─── system prompt constants & helpers ───────────────────────────────────────

/// All recognised prompt names (used to guard the upload/preview endpoints).
pub const VALID_PROMPT_NAMES: &[&str] = &[
    "voicemail_greeting_default",
    "beep",
    "vm_saved",
    "vm_menu",
    "vm_enter_extension",
    "vm_enter_pin",
    "vm_auth_failed",
    "vm_wrong_pin",
    "vm_error",
    "vm_no_messages",
    "vm_no_more_messages",
    "vm_deleted",
];

/// Resolve the **write** destination for a prompt override: always
/// `{sounds_dir}/{language}/{name}.wav` (creating the directory if needed).
fn prompt_write_path(cfg: &FileConfig, name: &str) -> std::path::PathBuf {
    std::path::Path::new(&cfg.voicemail.sounds_dir)
        .join(&cfg.voicemail.language)
        .join(format!("{}.wav", name))
}

/// Resolve the **read** path for a prompt using the same priority order as
/// `VoicemailSharedState::resolve_sound`.  Returns `None` if no file exists.
fn prompt_read_path(cfg: &FileConfig, name: &str) -> Option<std::path::PathBuf> {
    let base = std::path::Path::new(&cfg.voicemail.sounds_dir);
    let lang_path = base
        .join(&cfg.voicemail.language)
        .join(format!("{}.wav", name));
    if lang_path.exists() {
        return Some(lang_path);
    }
    let en_path = base.join("en").join(format!("{}.wav", name));
    if en_path.exists() {
        return Some(en_path);
    }
    let root_path = base.join(format!("{}.wav", name));
    if root_path.exists() {
        return Some(root_path);
    }
    None
}

/// Save raw audio bytes to the prompt override path, creating dirs as needed.
async fn write_prompt_file(dest: &std::path::Path, data: &[u8]) -> Result<(), String> {
    if let Some(parent) = dest.parent() {
        tokio::fs::create_dir_all(parent)
            .await
            .map_err(|e| format!("create dir: {}", e))?;
    }
    tokio::fs::write(dest, data)
        .await
        .map_err(|e| format!("write file: {}", e))
}

/// State shared across all voicemail HTTP handlers.
#[derive(Clone)]
pub struct VoicemailWebState {
    pub app: AppState,
    pub mailbox_svc: MailboxService,
    pub storage: Arc<VoicemailStorage>,
    /// Path to `config/voicemail.toml` for read/write from the settings page.
    pub config_path: std::path::PathBuf,
}

#[derive(Deserialize, Default)]
pub struct MessageListQuery {
    /// If set, restrict to unread messages only.
    pub unread: Option<bool>,
}

#[derive(Deserialize)]
pub struct CreateMailboxForm {
    pub extension: String,
    pub email: Option<String>,
    pub pin: String,
}

#[derive(Deserialize)]
pub struct ChangePinForm {
    pub old_pin: Option<String>,
    pub new_pin: String,
}

// ─── JSON response types ──────────────────────────────────────────────────────

#[derive(Serialize)]
struct MessageResponse {
    id: String,
    caller_id: String,
    duration: i32,
    read: bool,
    transcript: Option<String>,
    summary: Option<String>,
    created_at: String,
    audio_url: String,
}

impl From<&Message> for MessageResponse {
    fn from(m: &Message) -> Self {
        Self {
            id: m.id.to_string(),
            caller_id: m.caller_id.clone(),
            duration: m.duration,
            read: m.read,
            transcript: m.transcript.clone(),
            summary: m.summary.clone(),
            created_at: m.created_at.format("%Y-%m-%d %H:%M:%S").to_string(),
            audio_url: format!("/api/voicemail/messages/{}/audio", m.id),
        }
    }
}

// ─── helpers ─────────────────────────────────────────────────────────────────

fn console(state: &VoicemailWebState) -> &crate::console::ConsoleState {
    state.app.console.as_ref().expect("Console not initialized")
}

// ─── UI handlers ─────────────────────────────────────────────────────────────

/// GET /console/voicemail
///
/// Admin page: list all mailboxes with per-mailbox message counts.
pub async fn ui_list_mailboxes(
    State(state): State<VoicemailWebState>,
    headers: HeaderMap,
) -> Response {
    let db = state.mailbox_svc.db.clone();

    let mailboxes = MailboxEntity::find()
        .order_by(MailboxColumn::Extension, Order::Asc)
        .all(&db)
        .await
        .unwrap_or_default();

    // Fetch unread message counts for each mailbox.
    let mut rows = Vec::with_capacity(mailboxes.len());
    for mb in &mailboxes {
        let unread: u64 = MessageEntity::find()
            .filter(MessageColumn::BoxId.eq(mb.id))
            .filter(MessageColumn::Read.eq(false))
            .count(&db)
            .await
            .unwrap_or(0);
        let total: u64 = MessageEntity::find()
            .filter(MessageColumn::BoxId.eq(mb.id))
            .count(&db)
            .await
            .unwrap_or(0);
        rows.push(json!({
            "extension": mb.extension,
            "email": mb.email,
            "unread": unread,
            "total": total,
            "created_at": mb.created_at.format("%Y-%m-%d").to_string(),
        }));
    }

    let _lic = crate::license::get_license_status("voicemail");
    let license_valid = _lic.as_ref().map(|l| l.valid && !l.expired).unwrap_or(false);
    let license_expired = _lic.as_ref().map(|l| l.expired).unwrap_or(false);

    console(&state).render_with_headers(
        "voicemail/mailboxes.html",
        json!({
            "mailboxes": rows,
            "nav_active": "Voicemail",
            "license_valid": license_valid,
            "license_expired": license_expired,
        }),
        &headers,
    )
}

/// GET /console/voicemail/:extension
///
/// Admin page: messages for a single mailbox.
pub async fn ui_mailbox_messages(
    State(state): State<VoicemailWebState>,
    Path(extension): Path<String>,
    headers: HeaderMap,
) -> Response {
    let db = state.mailbox_svc.db.clone();

    let mailbox = match state.mailbox_svc.find_by_extension(&extension).await {
        Ok(Some(mb)) => mb,
        Ok(None) => {
            return Redirect::to("/console/voicemail").into_response();
        }
        Err(e) => {
            warn!(extension = %extension, "mailbox lookup failed: {}", e);
            return Redirect::to("/console/voicemail").into_response();
        }
    };

    // Unread first, then read; both by created_at DESC.
    let mut messages = MessageEntity::find()
        .filter(MessageColumn::BoxId.eq(mailbox.id))
        .filter(MessageColumn::Read.eq(false))
        .order_by(MessageColumn::CreatedAt, Order::Desc)
        .all(&db)
        .await
        .unwrap_or_default();

    let read = MessageEntity::find()
        .filter(MessageColumn::BoxId.eq(mailbox.id))
        .filter(MessageColumn::Read.eq(true))
        .order_by(MessageColumn::CreatedAt, Order::Desc)
        .all(&db)
        .await
        .unwrap_or_default();

    messages.extend(read);

    let msgs_json: Vec<_> = messages
        .iter()
        .map(|m| {
            json!({
                "id": m.id.to_string(),
                "caller_id": m.caller_id,
                "duration": m.duration,
                "read": m.read,
                "transcript": m.transcript,
                "summary": m.summary,
                "created_at": m.created_at.format("%Y-%m-%d %H:%M").to_string(),
                "audio_url": format!("/api/voicemail/messages/{}/audio", m.id),
            })
        })
        .collect();

    let unread_count = messages.iter().filter(|m| !m.read).count();

    console(&state).render_with_headers(
        "voicemail/messages.html",
        json!({
            "extension": extension,
            "email": mailbox.email,
            "has_greeting": mailbox.greeting_path.is_some(),
            "greeting_url": format!("/api/voicemail/mailboxes/{}/greeting", extension),
            "messages": msgs_json,
            "unread_count": unread_count,
            "nav_active": "Voicemail",
        }),
        &headers,
    )
}

// ─── form action handlers ─────────────────────────────────────────────────────

/// POST /console/voicemail/mailboxes
///
/// Create a new mailbox (admin action).
pub async fn form_create_mailbox(
    State(state): State<VoicemailWebState>,
    axum::Form(form): axum::Form<CreateMailboxForm>,
) -> Response {
    let email = form.email.as_deref().filter(|s| !s.is_empty());
    match state
        .mailbox_svc
        .create_mailbox(&form.extension, email, &form.pin)
        .await
    {
        Ok(_) => Redirect::to("/console/voicemail").into_response(),
        Err(e) => {
            warn!(extension = %form.extension, "create_mailbox failed: {}", e);
            // Return back to list with error (simple approach: redirect with flash not yet impl)
            Redirect::to("/console/voicemail").into_response()
        }
    }
}

/// POST /console/voicemail/mailboxes/:ext/delete
///
/// Delete a mailbox and all its messages (admin action).
pub async fn form_delete_mailbox(
    State(state): State<VoicemailWebState>,
    Path(extension): Path<String>,
) -> Response {
    let db = state.mailbox_svc.db.clone();

    if let Ok(Some(mb)) = state.mailbox_svc.find_by_extension(&extension).await {
        // Delete audio for all messages first (best-effort).
        if let Ok(msgs) = MessageEntity::find()
            .filter(MessageColumn::BoxId.eq(mb.id))
            .all(&db)
            .await
        {
            for msg in msgs {
                if let Err(e) = state.storage.delete_audio(&msg.audio_path).await {
                    warn!(audio_path = %msg.audio_path, "audio delete failed: {}", e);
                }
            }
        }

        // Delete the mailbox row (cascade deletes messages via FK).
        let active: MailboxActiveModel = mb.into();
        if let Err(e) = active.delete(&db).await {
            warn!(extension = %extension, "mailbox delete failed: {}", e);
        }
    }

    Redirect::to("/console/voicemail").into_response()
}

/// POST /console/voicemail/mailboxes/:ext/reset-pin
///
/// Admin PIN reset – returns the new PIN in a redirect header or as JSON.
pub async fn form_reset_pin(
    State(state): State<VoicemailWebState>,
    Path(extension): Path<String>,
) -> Response {
    match state.mailbox_svc.reset_pin(&extension).await {
        Ok(new_pin) => {
            // Show the new PIN via the detail page (simplistic). In production
            // this would be a flash message or a dedicated confirmation page.
            let location = format!(
                "/console/voicemail/{}?new_pin={}",
                urlencoding::encode(&extension),
                urlencoding::encode(&new_pin)
            );
            Redirect::to(&location).into_response()
        }
        Err(e) => {
            warn!(extension = %extension, "reset_pin failed: {}", e);
            Redirect::to("/console/voicemail").into_response()
        }
    }
}

/// POST /console/voicemail/messages/:id/delete
///
/// Delete a single message (admin or self-service).
pub async fn form_delete_message(
    State(state): State<VoicemailWebState>,
    Path(id): Path<Uuid>,
) -> Response {
    let db = state.mailbox_svc.db.clone();

    match MessageEntity::find_by_id(id).one(&db).await {
        Ok(Some(msg)) => {
            let ext = {
                // Resolve extension for redirect (best-effort).
                let mb = MailboxEntity::find_by_id(msg.box_id)
                    .one(&db)
                    .await
                    .ok()
                    .flatten();
                mb.map(|m| m.extension).unwrap_or_default()
            };

            if let Err(e) = state.storage.delete_audio(&msg.audio_path).await {
                warn!(audio_path = %msg.audio_path, "audio delete failed: {}", e);
            }

            let active: MessageActiveModel = msg.into();
            if let Err(e) = active.delete(&db).await {
                warn!(id = %id, "message delete failed: {}", e);
            }

            let location = format!("/console/voicemail/{}", urlencoding::encode(&ext));
            Redirect::to(&location).into_response()
        }
        _ => Redirect::to("/console/voicemail").into_response(),
    }
}

/// POST /console/voicemail/messages/:id/read
///
/// Mark a message as read (admin or self-service).
pub async fn form_mark_read(
    State(state): State<VoicemailWebState>,
    Path(id): Path<Uuid>,
) -> Response {
    let db = state.mailbox_svc.db.clone();

    if let Ok(Some(msg)) = MessageEntity::find_by_id(id).one(&db).await {
        let ext = {
            let mb = MailboxEntity::find_by_id(msg.box_id)
                .one(&db)
                .await
                .ok()
                .flatten();
            mb.map(|m| m.extension).unwrap_or_default()
        };

        if !msg.read {
            let mut active: MessageActiveModel = msg.into();
            active.read = Set(true);
            if let Err(e) = active.update(&db).await {
                warn!(id = %id, "mark_read failed: {}", e);
            }
        }

        let location = format!("/console/voicemail/{}", urlencoding::encode(&ext));
        Redirect::to(&location).into_response()
    } else {
        Redirect::to("/console/voicemail").into_response()
    }
}

// ─── REST / JSON API handlers ─────────────────────────────────────────────────

/// GET /api/voicemail/:extension/messages
///
/// JSON list of messages for an extension.
pub async fn api_list_messages(
    State(state): State<VoicemailWebState>,
    Path(extension): Path<String>,
    Query(q): Query<MessageListQuery>,
) -> Response {
    let db = state.mailbox_svc.db.clone();

    let mailbox = match state.mailbox_svc.find_by_extension(&extension).await {
        Ok(Some(mb)) => mb,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "mailbox not found"})),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": e.to_string()})),
            )
                .into_response();
        }
    };

    let mut query = MessageEntity::find()
        .filter(MessageColumn::BoxId.eq(mailbox.id))
        .order_by(MessageColumn::CreatedAt, Order::Desc);

    if let Some(true) = q.unread {
        query = query.filter(MessageColumn::Read.eq(false));
    }

    let messages = match query.all(&db).await {
        Ok(m) => m,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": e.to_string()})),
            )
                .into_response();
        }
    };

    let resp: Vec<MessageResponse> = messages.iter().map(MessageResponse::from).collect();
    Json(json!({ "extension": extension, "messages": resp })).into_response()
}

/// GET /api/voicemail/messages/:id/audio
///
/// Stream the raw audio bytes of a voicemail message.
/// Sets `Content-Type: audio/wav` and `Content-Disposition: attachment`.
pub async fn api_audio(State(state): State<VoicemailWebState>, Path(id): Path<Uuid>) -> Response {
    let db = state.mailbox_svc.db.clone();

    let msg = match MessageEntity::find_by_id(id).one(&db).await {
        Ok(Some(m)) => m,
        Ok(None) => {
            return (StatusCode::NOT_FOUND, "message not found").into_response();
        }
        Err(e) => {
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };

    // For local backends, serve the file directly from the path.
    if let Some(local_path) = state.storage.local_path(&msg.audio_path) {
        if local_path.exists() {
            match tokio::fs::read(&local_path).await {
                Ok(bytes) => {
                    let filename = local_path
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("voicemail.wav");
                    return (
                        [
                            (header::CONTENT_TYPE, "audio/wav"),
                            (
                                header::CONTENT_DISPOSITION,
                                &format!("attachment; filename=\"{}\"", filename),
                            ),
                        ],
                        bytes,
                    )
                        .into_response();
                }
                Err(e) => {
                    warn!(path = ?local_path, "failed to read audio: {}", e);
                    return (StatusCode::INTERNAL_SERVER_ERROR, "audio read failed")
                        .into_response();
                }
            }
        }
    }

    // S3 / fallback: load via storage backend.
    match state.storage.get_audio(&msg.audio_path).await {
        Ok(bytes) => {
            let filename = std::path::Path::new(&msg.audio_path)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("voicemail.wav")
                .to_string();
            (
                [
                    (header::CONTENT_TYPE, "audio/wav"),
                    (
                        header::CONTENT_DISPOSITION,
                        &format!("attachment; filename=\"{}\"", filename),
                    ),
                ],
                bytes.to_vec(),
            )
                .into_response()
        }
        Err(e) => {
            warn!(audio_path = %msg.audio_path, "audio fetch failed: {}", e);
            (StatusCode::NOT_FOUND, "audio not found").into_response()
        }
    }
}

// ─── settings page ────────────────────────────────────────────────────────────

/// GET /console/voicemail/settings
///
/// Admin settings page: edit all voicemail.toml fields via a web form.
pub async fn ui_settings(
    State(state): State<VoicemailWebState>,
    headers: HeaderMap,
) -> Response {
    let cfg = FileConfig::load(&state.config_path);

    let storage_type;
    let storage_path;
    let storage_bucket;
    let storage_region;
    let storage_access_key;
    let storage_vendor;
    let storage_endpoint;
    let storage_prefix;

    match &cfg.voicemail.storage {
        crate::addons::voicemail::storage::VoicemailStorageConfig::Local { path } => {
            storage_type = "local".to_string();
            storage_path = path.clone();
            storage_bucket = String::new();
            storage_region = String::new();
            storage_access_key = String::new();
            storage_vendor = String::new();
            storage_endpoint = String::new();
            storage_prefix = String::new();
        }
        crate::addons::voicemail::storage::VoicemailStorageConfig::S3 {
            vendor,
            bucket,
            region,
            access_key,
            endpoint,
            prefix,
            ..
        } => {
            storage_type = "s3".to_string();
            storage_path = String::new();
            storage_bucket = bucket.clone();
            storage_region = region.clone();
            storage_access_key = access_key.clone();
            // serde lowercase repr  e.g. S3Vendor::Minio → "minio"
            storage_vendor = toml::to_string(vendor)
                .unwrap_or_default()
                .trim_matches('"')
                .to_string();
            storage_endpoint = endpoint.clone().unwrap_or_default();
            storage_prefix = prefix.clone().unwrap_or_default();
        }
    }

    let _lic = crate::license::get_license_status("voicemail");
    let license_valid = _lic.as_ref().map(|l| l.valid && !l.expired).unwrap_or(false);
    let license_expired = _lic.as_ref().map(|l| l.expired).unwrap_or(false);

    console(&state).render_with_headers(
        "voicemail/settings.html",
        json!({
            "nav_active": "Voicemail",
            "license_valid": license_valid,
            "license_expired": license_expired,
            // recording
            "spool_dir": cfg.voicemail.spool_dir,
            "max_duration_secs": cfg.voicemail.max_duration_secs,
            "silence_timeout_secs": cfg.voicemail.silence_timeout_secs,
            // storage backend
            "storage_type": storage_type,
            "storage_path": storage_path,
            "storage_bucket": storage_bucket,
            "storage_region": storage_region,
            "storage_access_key": storage_access_key,
            "storage_vendor": storage_vendor,
            "storage_endpoint": storage_endpoint,
            "storage_prefix": storage_prefix,
            // storage policy
            "max_messages_per_mailbox": cfg.voicemail.max_messages_per_mailbox.unwrap_or(0),
            "max_age_days": cfg.voicemail.max_age_days.unwrap_or(0),
            "transcribe_enabled": cfg.voicemail.transcribe_enabled,
            // smtp
            "smtp_host": cfg.smtp_host(),
            "smtp_port": cfg.smtp_port(),
            "smtp_username": cfg.smtp_username(),
            "smtp_from": cfg.smtp_from(),
            "smtp_subject_template": cfg.smtp_subject_template(),
            "smtp_enabled": cfg.smtp_enabled(),
            // webhook
            "webhook_url": cfg.webhook_url_str(),
            // prompts / language
            "language": cfg.voicemail.language,
            "sounds_dir": cfg.voicemail.sounds_dir,
        }),
        &headers,
    )
}

/// POST /console/voicemail/settings
///
/// Save submitted settings form back to `config/voicemail.toml`.
pub async fn form_save_settings(
    State(state): State<VoicemailWebState>,
    axum::Form(form): axum::Form<SettingsForm>,
) -> Response {
    let existing = FileConfig::load(&state.config_path);
    let updated = form.apply_to(existing);
    if let Err(e) = updated.save(&state.config_path) {
        warn!(path = ?state.config_path, "save settings failed: {}", e);
    }
    Redirect::to("/console/voicemail/settings").into_response()
}

// ─── system prompt handlers ──────────────────────────────────────────────────

/// GET /api/voicemail/prompts/:name/audio
///
/// Stream a system prompt WAV for in-browser preview, resolving via
/// `sounds_dir` + `language` (same logic as `resolve_sound`).
pub async fn api_prompt_audio(
    State(state): State<VoicemailWebState>,
    Path(name): Path<String>,
) -> Response {
    if !VALID_PROMPT_NAMES.contains(&name.as_str()) {
        return (StatusCode::BAD_REQUEST, "unknown prompt name").into_response();
    }
    let cfg = FileConfig::load(&state.config_path);
    let path = match prompt_read_path(&cfg, &name) {
        Some(p) => p,
        None => return (StatusCode::NOT_FOUND, "prompt file not found").into_response(),
    };
    match tokio::fs::read(&path).await {
        Ok(bytes) => (
            [
                (header::CONTENT_TYPE, "audio/wav"),
                (header::CACHE_CONTROL, "no-cache"),
            ],
            bytes,
        )
            .into_response(),
        Err(e) => {
            warn!(path = ?path, "read prompt failed: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, "read failed").into_response()
        }
    }
}

/// POST /api/voicemail/prompts/:name/upload  (multipart, field name `file`)
///
/// Upload a WAV/MP3 replacement for a system prompt.  The file is saved to
/// `{sounds_dir}/{language}/{name}.wav`, overriding the built-in sound.
pub async fn api_prompt_upload(
    State(state): State<VoicemailWebState>,
    Path(name): Path<String>,
    mut multipart: Multipart,
) -> Response {
    if !VALID_PROMPT_NAMES.contains(&name.as_str()) {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "unknown prompt name"})),
        )
            .into_response();
    }
    let mut audio_bytes: Option<Vec<u8>> = None;
    while let Ok(Some(field)) = multipart.next_field().await {
        if field.name() == Some("file") {
            match field.bytes().await {
                Ok(b) if !b.is_empty() => audio_bytes = Some(b.to_vec()),
                _ => {}
            }
        }
    }
    let data = match audio_bytes {
        Some(b) => b,
        None => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": "no `file` field in multipart"})),
            )
                .into_response();
        }
    };
    let cfg = FileConfig::load(&state.config_path);
    let dest = prompt_write_path(&cfg, &name);
    match write_prompt_file(&dest, &data).await {
        Ok(()) => Json(json!({
            "ok": true,
            "path": dest.to_string_lossy()
        }))
        .into_response(),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e}))).into_response(),
    }
}

/// Request body for `api_prompt_from_url`.
#[derive(Deserialize)]
pub struct PromptUrlForm {
    pub url: String,
}

/// POST /api/voicemail/prompts/:name/from-url
///
/// Download audio from `url` and save it as a system prompt override.
/// Accepts `application/x-www-form-urlencoded` with a single `url` field.
pub async fn api_prompt_from_url(
    State(state): State<VoicemailWebState>,
    Path(name): Path<String>,
    axum::Form(form): axum::Form<PromptUrlForm>,
) -> Response {
    if !VALID_PROMPT_NAMES.contains(&name.as_str()) {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "unknown prompt name"})),
        )
            .into_response();
    }
    let bytes = match reqwest::get(&form.url).await {
        Ok(resp) if resp.status().is_success() => match resp.bytes().await {
            Ok(b) => b,
            Err(e) => {
                warn!(url = %form.url, "read prompt URL body failed: {}", e);
                return (
                    StatusCode::BAD_GATEWAY,
                    Json(json!({"error": "failed to read response body"})),
                )
                    .into_response();
            }
        },
        Ok(resp) => {
            return (
                StatusCode::BAD_GATEWAY,
                Json(json!({"error": format!("remote returned {}", resp.status())})),
            )
                .into_response();
        }
        Err(e) => {
            warn!(url = %form.url, "fetch prompt URL failed: {}", e);
            return (
                StatusCode::BAD_GATEWAY,
                Json(json!({"error": "fetch failed"})),
            )
                .into_response();
        }
    };
    let cfg = FileConfig::load(&state.config_path);
    let dest = prompt_write_path(&cfg, &name);
    match write_prompt_file(&dest, &bytes).await {
        Ok(()) => Json(json!({
            "ok": true,
            "path": dest.to_string_lossy()
        }))
        .into_response(),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e}))).into_response(),
    }
}

// ─── greeting management handlers ────────────────────────────────────────────

/// GET /api/voicemail/mailboxes/:ext/greeting
///
/// Stream the greeting audio for a mailbox (for the inline player).
pub async fn api_greeting_audio(
    State(state): State<VoicemailWebState>,
    Path(extension): Path<String>,
) -> Response {
    let mailbox = match state.mailbox_svc.find_by_extension(&extension).await {
        Ok(Some(mb)) => mb,
        Ok(None) => {
            return (StatusCode::NOT_FOUND, "mailbox not found").into_response();
        }
        Err(e) => {
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };

    let greeting_path = match mailbox.greeting_path {
        Some(p) => p,
        None => {
            return (StatusCode::NOT_FOUND, "no greeting set").into_response();
        }
    };

    // Try local path first.
    if let Some(local) = state.storage.local_path(&greeting_path) {
        if local.exists() {
            match tokio::fs::read(&local).await {
                Ok(bytes) => {
                    let filename = local
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("greeting.wav");
                    return (
                        [
                            (header::CONTENT_TYPE, "audio/wav"),
                            (
                                header::CONTENT_DISPOSITION,
                                &format!("inline; filename=\"{}\"", filename),
                            ),
                        ],
                        bytes,
                    )
                        .into_response();
                }
                Err(e) => {
                    warn!(path = ?local, "read greeting failed: {}", e);
                    return (StatusCode::INTERNAL_SERVER_ERROR, "read failed").into_response();
                }
            }
        }
    }

    // S3 fallback.
    match state.storage.get_greeting(&greeting_path).await {
        Ok(bytes) => {
            let filename = std::path::Path::new(&greeting_path)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("greeting.wav")
                .to_string();
            (
                [
                    (header::CONTENT_TYPE, "audio/wav"),
                    (
                        header::CONTENT_DISPOSITION,
                        &format!("inline; filename=\"{}\"", filename),
                    ),
                ],
                bytes.to_vec(),
            )
                .into_response()
        }
        Err(e) => {
            warn!(greeting = %greeting_path, "greeting fetch failed: {}", e);
            (StatusCode::NOT_FOUND, "greeting not found").into_response()
        }
    }
}

/// POST /console/voicemail/mailboxes/:ext/greeting  (multipart)
///
/// Upload a new greeting audio file for a mailbox.
pub async fn form_upload_greeting(
    State(state): State<VoicemailWebState>,
    Path(extension): Path<String>,
    mut multipart: Multipart,
) -> Response {
    let mailbox = match state.mailbox_svc.find_by_extension(&extension).await {
        Ok(Some(mb)) => mb,
        Ok(None) => {
            return Redirect::to(&format!(
                "/console/voicemail/{}",
                urlencoding::encode(&extension)
            ))
            .into_response();
        }
        Err(_) => {
            return Redirect::to("/console/voicemail").into_response();
        }
    };

    // Delete existing greeting from storage (best-effort).
    if let Some(old_path) = &mailbox.greeting_path {
        if let Err(e) = state.storage.delete_greeting(old_path).await {
            warn!(path = %old_path, "delete old greeting failed: {}", e);
        }
    }

    // Extract audio field from multipart.
    let mut audio_bytes: Option<Vec<u8>> = None;
    let mut file_ext = "wav".to_string();

    while let Ok(Some(field)) = multipart.next_field().await {
        if field.name() == Some("greeting") {
            // Detect extension from content-type header.
            if let Some(ct) = field.content_type() {
                file_ext = match ct {
                    "audio/mpeg" | "audio/mp3" => "mp3".to_string(),
                    "audio/ogg" => "ogg".to_string(),
                    _ => "wav".to_string(),
                };
            }
            match field.bytes().await {
                Ok(b) if !b.is_empty() => audio_bytes = Some(b.to_vec()),
                _ => {}
            }
        }
    }

    let data = match audio_bytes {
        Some(b) => b,
        None => {
            return Redirect::to(&format!(
                "/console/voicemail/{}",
                urlencoding::encode(&extension)
            ))
            .into_response();
        }
    };

    match state
        .storage
        .upload_greeting(&data, &extension, &file_ext)
        .await
    {
        Ok(key) => {
            if let Err(e) = state
                .mailbox_svc
                .set_greeting_path(&extension, Some(&key))
                .await
            {
                warn!(extension = %extension, "set_greeting_path failed: {}", e);
            }
        }
        Err(e) => {
            warn!(extension = %extension, "upload_greeting failed: {}", e);
        }
    }

    let location = format!("/console/voicemail/{}", urlencoding::encode(&extension));
    Redirect::to(&location).into_response()
}

/// POST /console/voicemail/mailboxes/:ext/greeting/delete
///
/// Delete the greeting for a mailbox.
pub async fn form_delete_greeting(
    State(state): State<VoicemailWebState>,
    Path(extension): Path<String>,
) -> Response {
    if let Ok(Some(mailbox)) = state.mailbox_svc.find_by_extension(&extension).await {
        if let Some(path) = &mailbox.greeting_path {
            if let Err(e) = state.storage.delete_greeting(path).await {
                warn!(path = %path, "delete greeting failed: {}", e);
            }
        }
        if let Err(e) = state.mailbox_svc.set_greeting_path(&extension, None).await {
            warn!(extension = %extension, "clear greeting_path failed: {}", e);
        }
    }

    let location = format!("/console/voicemail/{}", urlencoding::encode(&extension));
    Redirect::to(&location).into_response()
}