scribe-client 0.3.1

Rust client for the Scribe document conversion API
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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
use scribe_client::{DocumentSource, OutputFormat, ScribeClient, ScribeError, TokenSet};
use time::OffsetDateTime;
use url::Url;
use wiremock::{
    matchers::{body_string_contains, header, method, path},
    Mock, MockServer, ResponseTemplate,
};

fn valid_tokens() -> TokenSet {
    TokenSet {
        access_token: "at-valid".into(),
        refresh_token: Some("rt-valid".into()),
        expires_at: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
    }
}

fn client_for(server: &MockServer, tokens: TokenSet) -> ScribeClient {
    ScribeClient::new(
        reqwest::Client::new(),
        Url::parse(&server.uri()).unwrap(),
        "test-client-id",
        tokens,
    )
}

#[tokio::test]
async fn create_document_from_file_returns_document_id() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "document_id": "doc-1"
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let doc = client
        .create_document(
            DocumentSource::File {
                file_name: "report.docx".into(),
                bytes: b"pretend docx bytes".to_vec(),
            },
            None,
        )
        .await
        .unwrap();
    assert_eq!(doc.document_id, "doc-1");
}

#[tokio::test]
async fn list_outputs_parses_in_progress_and_complete_rows() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "outputs": [
                {
                    "format": "html_stream",
                    "stage": "convert",
                    "progress": 0.5,
                    "estimated_time_remaining": 10,
                    "is_preview": true,
                    "downloadable": false
                },
                {
                    "format": "pdf",
                    "stage": "complete",
                    "progress": 1.0,
                    "estimated_time_remaining": null,
                    "is_preview": false
                }
            ]
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let outputs = client.list_outputs("doc-1").await.unwrap().outputs;
    assert_eq!(outputs.len(), 2);
    assert_eq!(outputs[0].format, OutputFormat::HtmlStream);
    assert!(!outputs[0].stage.is_complete());
    assert_eq!(outputs[1].format, OutputFormat::Pdf);
    assert!(outputs[1].stage.is_complete());
    assert!(!outputs[0].downloadable);
    // A server from before the field existed still offers the download.
    assert!(outputs[1].downloadable);
}

#[tokio::test]
async fn download_output_returns_bytes_when_complete() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/pdf/download"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(b"%PDF-1.4 fake".to_vec()))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let download = client
        .download_output("doc-1", OutputFormat::Pdf)
        .await
        .unwrap();
    assert_eq!(download.data, b"%PDF-1.4 fake".to_vec());
    assert_eq!(download.file_name, None);
}

async fn file_name_from_header(header: &str) -> Option<String> {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/mp3/download"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-disposition", header)
                .set_body_bytes(b"ID3".to_vec()),
        )
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    client
        .download_output("doc-1", OutputFormat::Mp3)
        .await
        .unwrap()
        .file_name
}

/// The exact header the server sends for the QA report's document.
#[tokio::test]
async fn download_output_prefers_the_utf8_file_name() {
    let name = file_name_from_header(
        r#"attachment; filename="SensePlayer User Manual (Model - T90ET).mp3"; filename*=UTF-8''SensePlayer%E2%84%A2%20User%20Manual%20%28Model%20-%20T90ET%29.mp3"#,
    )
    .await;
    assert_eq!(
        name.as_deref(),
        Some("SensePlayer\u{2122} User Manual (Model - T90ET).mp3")
    );
}

/// The server leaves "+" unencoded, so it must not be read as a space.
#[tokio::test]
async fn download_output_keeps_a_literal_plus() {
    let name = file_name_from_header(
        r#"attachment; filename="C++ Notes.pdf"; filename*=UTF-8''C++%20Notes.pdf"#,
    )
    .await;
    assert_eq!(name.as_deref(), Some("C++ Notes.pdf"));
}

#[tokio::test]
async fn download_output_falls_back_to_the_ascii_file_name() {
    let name = file_name_from_header(r#"attachment; filename="Report.html""#).await;
    assert_eq!(name.as_deref(), Some("Report.html"));
}

#[tokio::test]
async fn download_output_drops_any_folders_in_the_file_name() {
    let name = file_name_from_header(r#"attachment; filename*=UTF-8''..%2F..%2FReport.pdf"#).await;
    assert_eq!(name.as_deref(), Some("Report.pdf"));
}

#[tokio::test]
async fn download_output_reports_progress_with_a_total() {
    let server = MockServer::start().await;
    let body = vec![7u8; 4096];
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/mp3/download"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone()))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let mut reports: Vec<(u64, Option<u64>)> = Vec::new();
    let download = client
        .download_output_with_progress("doc-1", OutputFormat::Mp3, |downloaded, total| {
            reports.push((downloaded, total));
        })
        .await
        .unwrap();

    assert_eq!(download.data.len(), body.len());
    assert_eq!(reports.first(), Some(&(0, Some(4096))));
    assert_eq!(reports.last(), Some(&(4096, Some(4096))));
}

/// The real body's length wins over anything else a response claims. The
/// `x-scribe-content-length` fallback only applies to a chunked response,
/// which has no Content-Length at all and which wiremock cannot produce.
#[tokio::test]
async fn download_output_prefers_the_real_content_length() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/mp3/download"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("x-scribe-content-length", "9000")
                .set_body_bytes(vec![1u8; 256]),
        )
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let mut totals: Vec<Option<u64>> = Vec::new();
    client
        .download_output_with_progress("doc-1", OutputFormat::Mp3, |_, total| totals.push(total))
        .await
        .unwrap();

    assert!(
        totals.iter().all(|total| *total == Some(256)),
        "expected the body's own length, got {totals:?}"
    );
}

/// Without any size, progress still reports bytes so a caller can show
/// something moving.
#[tokio::test]
async fn download_output_reports_bytes_without_a_total() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/brf/download"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![3u8; 512]))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let mut last = 0u64;
    client
        .download_output_with_progress("doc-1", OutputFormat::Brf, |downloaded, _| {
            last = downloaded;
        })
        .await
        .unwrap();
    assert_eq!(last, 512);
}

/// The API redirects to storage by default, so a player can stream from there.
#[tokio::test]
async fn download_url_reports_where_the_file_really_lives() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/mp3/download"))
        .respond_with(ResponseTemplate::new(302).insert_header(
            "location",
            "https://storage.example/doc-1.mp3?signature=abc",
        ))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let url = client
        .download_url("doc-1", OutputFormat::Mp3)
        .await
        .unwrap();
    assert_eq!(
        url.as_deref(),
        Some("https://storage.example/doc-1.mp3?signature=abc")
    );
}

/// A server that sends the file itself says so by not redirecting, and the
/// caller downloads it first instead.
#[tokio::test]
async fn download_url_is_none_when_the_server_sends_the_file() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/mp3/download"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(b"ID3".to_vec()))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    assert_eq!(
        client
            .download_url("doc-1", OutputFormat::Mp3)
            .await
            .unwrap(),
        None
    );
}

#[tokio::test]
async fn download_url_maps_conversion_not_complete() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/mp3/download"))
        .respond_with(ResponseTemplate::new(409).set_body_json(serde_json::json!({
            "error": {"code": "conversion_not_complete", "message": "This file isn't ready yet."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.download_url("doc-1", OutputFormat::Mp3).await;
    assert!(matches!(
        result,
        Err(ScribeError::ConversionNotComplete { .. })
    ));
}

#[tokio::test]
async fn download_output_maps_conversion_not_complete() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs/pdf/download"))
        .respond_with(ResponseTemplate::new(409).set_body_json(serde_json::json!({
            "error": {"code": "conversion_not_complete", "message": "This file isn't ready yet."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.download_output("doc-1", OutputFormat::Pdf).await;
    assert!(matches!(
        result,
        Err(ScribeError::ConversionNotComplete { .. })
    ));
}

#[tokio::test]
async fn create_document_from_url_returns_document_id() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "document_id": "doc-2"
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let doc = client
        .create_document(
            DocumentSource::Url("https://example.com/report.pdf".into()),
            None,
        )
        .await
        .unwrap();
    assert_eq!(doc.document_id, "doc-2");
}

#[tokio::test]
async fn list_outputs_maps_not_found() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/missing/outputs"))
        .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
            "error": {"code": "not_found", "message": "We couldn't find that."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.list_outputs("missing").await;
    assert!(matches!(result, Err(ScribeError::NotFound { .. })));
}

#[tokio::test]
async fn list_outputs_maps_forbidden() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/other-users-doc/outputs"))
        .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
            "error": {"code": "forbidden", "message": "You don't have permission to do that."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.list_outputs("other-users-doc").await;
    assert!(matches!(result, Err(ScribeError::Forbidden { .. })));
}

#[tokio::test]
async fn list_outputs_maps_unrecognized_error_to_api_variant() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
            "error": {"code": "internal_error", "message": "Something broke upstream."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.list_outputs("doc-1").await;
    match result {
        Err(ScribeError::Api {
            status,
            code,
            message,
        }) => {
            assert_eq!(status, 500);
            assert_eq!(code, "internal_error");
            assert_eq!(message, "Something broke upstream.");
        }
        other => panic!("expected Api error, got {other:?}"),
    }
}

#[tokio::test]
async fn a_second_401_after_refresh_is_not_retried_again() {
    let server = MockServer::start().await;
    // Every request gets a 401, including the retry after refresh: the
    // client must not loop forever, so the second 401 should surface as
    // an HTTP error rather than triggering another refresh attempt.
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/oauth/token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "access_token": "at-fresh",
            "refresh_token": "rt-fresh",
            "expires_in": 3600
        })))
        .mount(&server)
        .await;
    let stale_tokens = TokenSet {
        access_token: "at-stale".into(),
        refresh_token: Some("rt-stale".into()),
        expires_at: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
    };
    let client = client_for(&server, stale_tokens);
    let result = client.list_outputs("doc-1").await;
    // The second 401 has no JSON body, so it should surface as a generic
    // Api error with status 401 rather than panicking or looping.
    assert!(matches!(result, Err(ScribeError::Api { status: 401, .. })));
}

#[tokio::test]
async fn a_401_with_no_refresh_token_available_surfaces_invalid_grant() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;
    let tokens_without_refresh = TokenSet {
        access_token: "at-stale".into(),
        refresh_token: None,
        expires_at: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
    };
    let client = client_for(&server, tokens_without_refresh);
    let result = client.list_outputs("doc-1").await;
    assert!(matches!(result, Err(ScribeError::InvalidGrant { .. })));
}

#[tokio::test]
async fn proactive_refresh_happens_before_expiry_without_a_401() {
    let server = MockServer::start().await;
    // No mock for the stale token: if the client didn't proactively refresh
    // (it's within REFRESH_SKEW of expiring), this request would 404 against
    // wiremock's default "no matching mock" response.
    Mock::given(method("POST"))
        .and(path("/oauth/token"))
        .and(body_string_contains("grant_type=refresh_token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "access_token": "at-fresh",
            "refresh_token": "rt-fresh",
            "expires_in": 3600
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .and(header("authorization", "Bearer at-fresh"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(serde_json::json!({ "outputs": [] })),
        )
        .mount(&server)
        .await;
    let about_to_expire = TokenSet {
        access_token: "at-stale".into(),
        refresh_token: Some("rt-stale".into()),
        expires_at: Some(OffsetDateTime::now_utc() + time::Duration::seconds(5)),
    };
    let client = client_for(&server, about_to_expire);
    let outputs = client.list_outputs("doc-1").await.unwrap().outputs;
    assert!(outputs.is_empty());
}

#[tokio::test]
async fn a_401_triggers_refresh_and_retries_once() {
    let server = MockServer::start().await;
    // The initial (stale) token gets a 401, which triggers a refresh, and
    // the retry with the new token succeeds.
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .and(header("authorization", "Bearer at-stale"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/oauth/token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "access_token": "at-fresh",
            "refresh_token": "rt-fresh",
            "expires_in": 3600
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .and(header("authorization", "Bearer at-fresh"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(serde_json::json!({ "outputs": [] })),
        )
        .mount(&server)
        .await;
    let stale_tokens = TokenSet {
        access_token: "at-stale".into(),
        refresh_token: Some("rt-stale".into()),
        expires_at: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
    };
    let client = client_for(&server, stale_tokens);
    let outputs = client.list_outputs("doc-1").await.unwrap().outputs;
    assert!(outputs.is_empty());
}

#[tokio::test]
async fn list_documents_parses_documents_with_embedded_outputs() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "documents": [
                {
                    "id": "doc-1",
                    "title": "Report",
                    "page_count": 3,
                    "inserted_at": "2026-07-08T20:04:24.000000Z",
                    "outputs": [
                        {
                            "format": "html_stream",
                            "stage": "complete",
                            "progress": 1.0,
                            "estimated_time_remaining": null,
                            "is_preview": false
                        }
                    ]
                }
            ]
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let documents = client.list_documents().await.unwrap().documents;
    assert_eq!(documents.len(), 1);
    assert_eq!(documents[0].id, "doc-1");
    assert_eq!(documents[0].title.as_deref(), Some("Report"));
    assert_eq!(documents[0].page_count, Some(3));
    assert_eq!(documents[0].outputs.len(), 1);
    assert_eq!(documents[0].outputs[0].format, OutputFormat::HtmlStream);
}

#[tokio::test]
async fn list_documents_handles_a_null_title() {
    // A URL-sourced document has no title until the converter determines
    // one; the server returns `"title": null` for it.
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/documents"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "documents": [
                {
                    "id": "doc-1",
                    "title": null,
                    "page_count": null,
                    "inserted_at": "2026-07-09T13:19:30.000000Z",
                    "outputs": []
                }
            ]
        })))
        .mount(&server)
        .await;

    let client = client_for(&server, valid_tokens());
    let documents = client.list_documents().await.unwrap().documents;

    assert_eq!(documents[0].title, None);
}

#[tokio::test]
async fn trash_document_succeeds_on_204() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents/doc-1/trash"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(204))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    client.trash_document("doc-1").await.unwrap();
}

#[tokio::test]
async fn trash_document_maps_not_found() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents/missing/trash"))
        .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
            "error": {"code": "not_found", "message": "We couldn't find that."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.trash_document("missing").await;
    assert!(matches!(result, Err(ScribeError::NotFound { .. })));
}

#[tokio::test]
async fn trash_document_maps_forbidden() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents/doc-1/trash"))
        .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
            "error": {"code": "forbidden", "message": "You don't have permission to do that."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.trash_document("doc-1").await;
    assert!(matches!(result, Err(ScribeError::Forbidden { .. })));
}

#[tokio::test]
async fn delete_document_permanently_succeeds_on_204() {
    let server = MockServer::start().await;
    Mock::given(method("DELETE"))
        .and(path("/api/documents/doc-1"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(204))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    client.delete_document_permanently("doc-1").await.unwrap();
}

#[tokio::test]
async fn delete_document_permanently_maps_not_trashed() {
    let server = MockServer::start().await;
    Mock::given(method("DELETE"))
        .and(path("/api/documents/doc-1"))
        .respond_with(ResponseTemplate::new(409).set_body_json(serde_json::json!({
            "error": {"code": "not_trashed", "message": "This document isn't in the trash."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.delete_document_permanently("doc-1").await;
    assert!(matches!(result, Err(ScribeError::NotTrashed { .. })));
}

#[tokio::test]
async fn recover_document_succeeds_on_204() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents/doc-1/recover"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(204))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    client.recover_document("doc-1").await.unwrap();
}

#[tokio::test]
async fn recover_document_maps_not_found() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents/missing/recover"))
        .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
            "error": {"code": "not_found", "message": "We couldn't find that."}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let result = client.recover_document("missing").await;
    assert!(matches!(result, Err(ScribeError::NotFound { .. })));
}

#[tokio::test]
async fn list_trashed_documents_parses_rows() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/trash"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "documents": [
                {
                    "id": "doc-1",
                    "title": "Report",
                    "page_count": 3,
                    "inserted_at": "2026-07-08T20:04:24.000000Z",
                    "trashed_at": "2026-08-03T13:46:26.000000Z",
                    "permanently_delete_at": "2026-08-10T13:46:26.000000Z"
                }
            ]
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let documents = client.list_trashed_documents().await.unwrap();
    assert_eq!(documents.len(), 1);
    assert_eq!(documents[0].id, "doc-1");
    assert_eq!(documents[0].trashed_at, "2026-08-03T13:46:26.000000Z");
    assert_eq!(
        documents[0].permanently_delete_at,
        "2026-08-10T13:46:26.000000Z"
    );
}

#[tokio::test]
async fn list_outputs_reports_a_locked_document() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents/doc-1/outputs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "outputs": [],
            "is_password_needed": true
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let list = client.list_outputs("doc-1").await.unwrap();
    assert!(list.outputs.is_empty());
    assert!(list.is_password_needed);
}

#[tokio::test]
async fn list_documents_reads_whether_to_suggest_buying_pages() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "documents": [],
            "pages_remaining": 12,
            "suggest_buying_pages": true
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    assert!(client.list_documents().await.unwrap().suggest_buying_pages);
}

#[tokio::test]
async fn list_documents_does_not_suggest_buying_when_the_server_does_not_say() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "documents": [],
            "pages_remaining": 12
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    assert!(!client.list_documents().await.unwrap().suggest_buying_pages);
}

#[tokio::test]
async fn list_documents_reports_a_locked_document() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/documents"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "documents": [
                {
                    "id": "doc-1",
                    "title": "Locked",
                    "page_count": null,
                    "inserted_at": "2026-09-15T00:00:00Z",
                    "is_password_needed": true,
                    "outputs": []
                }
            ],
            "pages_remaining": 3
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let list = client.list_documents().await.unwrap();
    assert!(list.documents[0].is_password_needed);
}

#[tokio::test]
async fn create_document_sends_a_password_when_one_is_given() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/documents"))
        .and(body_string_contains("document[password]"))
        .and(body_string_contains("hunter2"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "document_id": "doc-1"
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let doc = client
        .create_document(
            DocumentSource::File {
                file_name: "locked.pdf".into(),
                bytes: b"%PDF".to_vec(),
            },
            Some("hunter2"),
        )
        .await
        .unwrap();
    assert_eq!(doc.document_id, "doc-1");
}

fn document_json(title: &str) -> serde_json::Value {
    serde_json::json!({
        "id": "doc-1",
        "title": title,
        "page_count": 3,
        "inserted_at": "2026-09-18T15:04:05.000000Z",
        "is_password_needed": false,
        "outputs": []
    })
}

#[tokio::test]
async fn rename_document_patches_the_document_and_returns_it() {
    let server = MockServer::start().await;
    Mock::given(method("PATCH"))
        .and(path("/api/documents/doc-1"))
        .and(header("authorization", "Bearer at-valid"))
        // The server reads the title out of a nested "document" object, the
        // same shape its own form posts. A flat {"title": ...} is ignored.
        .and(body_string_contains(
            r#""document":{"title":"Quarterly Earnings"}"#,
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(document_json("Quarterly Earnings")))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let document = client
        .rename_document("doc-1", "Quarterly Earnings")
        .await
        .unwrap();
    assert_eq!(document.title.as_deref(), Some("Quarterly Earnings"));
    assert_eq!(document.id, "doc-1");
}

#[tokio::test]
async fn rename_document_maps_a_rejected_title_to_an_api_error() {
    let server = MockServer::start().await;
    Mock::given(method("PATCH"))
        .and(path("/api/documents/doc-1"))
        .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
            "error": {"code": "unprocessable_entity", "message": "Title can't be blank"}
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let error = client.rename_document("doc-1", "").await.unwrap_err();
    assert!(
        matches!(error, ScribeError::Api { ref message, .. } if message.contains("blank")),
        "got {error:?}"
    );
}

#[tokio::test]
async fn billing_reads_pages_subscription_and_account_token() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/billing"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "pages_remaining": 9800,
            "subscription": {"store": "app_store", "renews_at": "2027-10-29T12:00:00.000000Z"},
            "app_account_token": "6f1c9a52-3e1b-4a8e-9f5d-2b7c8e4d1a00"
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let billing = client.billing().await.unwrap();
    assert_eq!(billing.pages_remaining, 9800);
    let subscription = billing.subscription.unwrap();
    assert_eq!(subscription.store, "app_store");
    assert_eq!(
        subscription.renews_at.as_deref(),
        Some("2027-10-29T12:00:00.000000Z")
    );
    assert_eq!(
        billing.app_account_token,
        "6f1c9a52-3e1b-4a8e-9f5d-2b7c8e4d1a00"
    );
}

#[tokio::test]
async fn billing_reads_an_account_without_a_subscription() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/billing"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "pages_remaining": 0,
            "subscription": null,
            "app_account_token": "6f1c9a52-3e1b-4a8e-9f5d-2b7c8e4d1a00"
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    assert!(client.billing().await.unwrap().subscription.is_none());
}

#[tokio::test]
async fn app_store_products_lists_what_is_on_sale_in_the_servers_order() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/app_store/products"))
        .and(header("authorization", "Bearer at-valid"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "products": [
                {"id": "com.example.pages.500", "kind": "page_pack", "pages": 500},
                {"id": "com.example.pages.200", "kind": "page_pack", "pages": 200},
                {"id": "com.example.yearly", "kind": "subscription", "pages": 10000}
            ]
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let products = client.app_store_products().await.unwrap();
    let ids: Vec<&str> = products.iter().map(|p| p.id.as_str()).collect();
    assert_eq!(
        ids,
        [
            "com.example.pages.500",
            "com.example.pages.200",
            "com.example.yearly"
        ]
    );
    assert_eq!(products[2].kind, "subscription");
    assert_eq!(products[2].pages, 10_000);
}

#[tokio::test]
async fn submit_app_store_transaction_posts_the_jws_and_returns_the_new_balance() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/app_store/transactions"))
        .and(header("authorization", "Bearer at-valid"))
        .and(body_string_contains(
            r#""signed_transaction":"header.payload.signature""#,
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "pages_remaining": 200,
            "subscription": null,
            "app_account_token": "6f1c9a52-3e1b-4a8e-9f5d-2b7c8e4d1a00"
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let billing = client
        .submit_app_store_transaction("header.payload.signature")
        .await
        .unwrap();
    assert_eq!(billing.pages_remaining, 200);
}

#[tokio::test]
async fn submit_app_store_transaction_reports_a_purchase_made_by_another_account() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/app_store/transactions"))
        .respond_with(ResponseTemplate::new(409).set_body_json(serde_json::json!({
            "error": {
                "code": "other_account",
                "message": "This purchase belongs to a different Scribe account."
            }
        })))
        .mount(&server)
        .await;
    let client = client_for(&server, valid_tokens());
    let error = client
        .submit_app_store_transaction("header.payload.signature")
        .await
        .unwrap_err();
    assert!(
        matches!(error, ScribeError::Api { status: 409, ref code, .. } if code == "other_account"),
        "got {error:?}"
    );
}

fn query_params(url: &str) -> std::collections::HashMap<String, String> {
    Url::parse(url)
        .unwrap()
        .query_pairs()
        .into_owned()
        .collect()
}

#[tokio::test]
async fn delete_account_url_signs_the_browser_in_and_lands_on_the_settings_page() {
    let server = MockServer::start().await;
    let client = client_for(&server, valid_tokens());
    let url = client.delete_account_url().await.unwrap();

    let parsed = Url::parse(&url).unwrap();
    assert_eq!(parsed.path(), "/auth/browser_from_oauth");
    let params = query_params(&url);
    assert_eq!(params.get("token").map(String::as_str), Some("at-valid"));
    // The page is under /settings, not a top-level /delete_account.
    assert_eq!(
        params
            .get("state")
            .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok()),
        Some(serde_json::json!({ "return_to": scribe_client::DELETE_ACCOUNT_PATH }))
    );
    assert_eq!(
        scribe_client::DELETE_ACCOUNT_PATH,
        "/settings/delete_account"
    );
}

/// The server answers a stale token with a "Failed to log in" page, which is
/// exactly where the user would land. So the URL has to carry a fresh one.
#[tokio::test]
async fn delete_account_url_refreshes_a_token_that_is_about_to_expire() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/oauth/token"))
        .and(body_string_contains("grant_type=refresh_token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "access_token": "at-fresh",
            "refresh_token": "rt-fresh",
            "expires_in": 3600
        })))
        .mount(&server)
        .await;
    let about_to_expire = TokenSet {
        access_token: "at-stale".into(),
        refresh_token: Some("rt-stale".into()),
        expires_at: Some(OffsetDateTime::now_utc() + time::Duration::seconds(5)),
    };
    let client = client_for(&server, about_to_expire);
    let url = client.delete_account_url().await.unwrap();
    assert_eq!(
        query_params(&url).get("token").map(String::as_str),
        Some("at-fresh")
    );
}

#[tokio::test]
async fn browser_entry_url_escapes_awkward_values() {
    let server = MockServer::start().await;
    let client = client_for(&server, valid_tokens());
    let url = client
        .browser_entry_url("/some path?a=b&c=d")
        .await
        .unwrap();
    // It must round-trip exactly, or the redirect after sign-in goes astray.
    assert_eq!(
        query_params(&url)
            .get("state")
            .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok()),
        Some(serde_json::json!({ "return_to": "/some path?a=b&c=d" }))
    );
}