realitydefender 0.1.8

Reality Defender SDK for Rust - Tools for detecting deepfakes and manipulated media
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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
use crate::config::Config;
use crate::error::{Error, Result};
use crate::file::SUPPORTED_FILE_TYPES;
use crate::http::api_paths::SOCIAL_MEDIA;
use crate::models::{BaseResponse, UploadSocialMediaOptions};
use crate::utils::{determine_content_type, is_valid_url};
use crate::UploadResult;
use reqwest::{Client as ReqwestClient, ClientBuilder, Response, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::path::Path;
use std::time::Duration;

/// Constants for API paths
pub mod api_paths {
    /// Path for requesting a presigned upload URL
    pub const SIGNED_URL: &str = "/api/files/aws-presigned";
    /// Path for retrieving media results
    pub const MEDIA_RESULT: &str = "/api/media/users";
    /// Path for retrieving all media results with pagination
    pub const ALL_MEDIA_RESULTS: &str = "/api/v2/media/users/pages";
    // Path for posting social media links
    pub const SOCIAL_MEDIA: &str = "/api/files/social";
}

/// HTTP client for making API requests
pub struct HttpClient {
    client: ReqwestClient,
    config: Config,
}

impl HttpClient {
    /// Create a new HTTP client with the given configuration
    pub fn new(config: Config) -> Result<Self> {
        config.validate()?;

        // Use the same User-Agent as Go SDK might be using
        let client = ClientBuilder::new()
            .user_agent("realitydefender-go-sdk/1.0")
            .timeout(Duration::from_secs(config.get_timeout_seconds()))
            .build()?;

        Ok(Self { client, config })
    }

    /// Make a GET request to the specified endpoint
    pub async fn get<T: DeserializeOwned>(&self, endpoint: &str) -> Result<T> {
        let url = format!("{}{}", self.config.get_base_url(), endpoint);

        let request = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.config.api_key)
            .header("Accept", "application/json")
            .header("Accept-Encoding", "gzip")
            .build()?;

        let response = self.client.execute(request).await?;
        self.handle_response(response).await
    }

    /// Make a GET request with query parameters to the specified endpoint
    pub async fn get_with_params<T: DeserializeOwned>(
        &self,
        endpoint: &str,
        params: &[(&str, &str)],
    ) -> Result<T> {
        let url = format!("{}{}", self.config.get_base_url(), endpoint);

        let request = self
            .client
            .get(&url)
            .query(params)
            .header("X-API-KEY", &self.config.api_key)
            .header("Accept", "application/json")
            .header("Accept-Encoding", "gzip")
            .build()?;

        let response = self.client.execute(request).await?;
        self.handle_response(response).await
    }

    /// Make a POST request with JSON data to the specified endpoint
    pub async fn post<T: DeserializeOwned, D: Serialize>(
        &self,
        endpoint: &str,
        data: &D,
    ) -> Result<T> {
        let url = format!("{}{}", self.config.get_base_url(), endpoint);

        let request = self
            .client
            .post(&url)
            .header("X-API-KEY", &self.config.api_key)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("Accept-Encoding", "gzip")
            .json(data)
            .build()?;

        let response = self.client.execute(request).await?;
        self.handle_response(response).await
    }

    /// Make a PUT request to upload data to a URL (used for presigned URLs)
    pub async fn put(&self, url: &str, data: Vec<u8>, content_type: &str) -> Result<()> {
        let request = self
            .client
            .put(url)
            .header("Content-Type", content_type)
            .header("Content-Length", data.len().to_string())
            // Do not include X-API-KEY for presigned URL uploads
            .body(data.clone())
            .build()?;

        let response = self.client.execute(request).await?;
        let status = response.status();

        // Check if the upload was successful
        if !status.is_success() {
            let body = response.text().await?;
            return Err(Error::UploadFailed(format!(
                "Failed to upload to presigned URL. Status: {status} Body: {body}"
            )));
        }

        Ok(())
    }

    /// Upload a file using the presigned URL flow
    pub async fn upload_file<T: DeserializeOwned>(&self, file_path: &str) -> Result<T> {
        // 1. Get file name
        let path = Path::new(file_path);
        if !path.exists() {
            return Err(Error::InvalidFile(format!("File not found: {file_path}")));
        }

        let file_extension = path
            .extension()
            .ok_or_else(|| Error::InvalidFile("Invalid file name".to_string()))?;
        let supported_file_type = SUPPORTED_FILE_TYPES
            .iter()
            .find(|x| x.extensions.contains(&file_extension.to_str().unwrap()));

        if supported_file_type.is_none() {
            return Err(Error::InvalidFile(format!(
                "Unsupported file type: {file_path}"
            )));
        }

        let file_size = path.metadata()?.len();
        if file_size > supported_file_type.unwrap().size_limit {
            return Err(Error::InvalidFile(format!("File too large: {file_path}")));
        }

        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| Error::InvalidFile("Invalid file name".to_string()))?;

        let payload = serde_json::json!({ "fileName": file_name });

        // 2. Request a presigned URL
        let signed_url_response = self
            .post::<crate::models::SignedUrlResponse, _>(api_paths::SIGNED_URL, &payload)
            .await?;

        // 3. Read the file content
        let file_content = tokio::fs::read(path).await?;

        // Check if file is empty or if there's an issue reading it
        if file_content.is_empty() {
            // Try with std::fs to see if it reads the file correctly
            let std_file_content = std::fs::read(path)?;

            if std_file_content.is_empty() {
                return Err(Error::InvalidFile(format!("File is empty: {file_path}")));
            }

            // Use the content read by std::fs instead
            return self
                .upload_file_with_content(signed_url_response, std_file_content, path)
                .await;
        }

        // 4. Determine content type based on file extension
        let content_type = determine_content_type(path);

        // 5. Upload to the presigned URL
        self.put(
            &signed_url_response.response.signed_url,
            file_content,
            content_type,
        )
        .await?;

        // 6. Create upload result with request_id and media_id
        let upload_result = UploadResult {
            request_id: signed_url_response.request_id,
            media_id: Option::from(signed_url_response.media_id),
            result_url: None,
        };

        // 7. Convert to the requested type
        Ok(serde_json::from_value(serde_json::to_value(
            upload_result,
        )?)?)
    }

    /// Helper method to upload file with provided content
    async fn upload_file_with_content<T: DeserializeOwned>(
        &self,
        signed_url_response: crate::models::SignedUrlResponse,
        file_content: Vec<u8>,
        path: &Path,
    ) -> Result<T> {
        // Determine content type based on file extension
        let content_type = determine_content_type(path);

        // Upload to the presigned URL
        self.put(
            &signed_url_response.response.signed_url,
            file_content,
            content_type,
        )
        .await?;

        // Create upload result with request_id and media_id
        let upload_result = UploadResult {
            request_id: signed_url_response.request_id,
            media_id: Option::from(signed_url_response.media_id),
            result_url: None,
        };

        // Convert to the requested type
        Ok(serde_json::from_value(serde_json::to_value(
            upload_result,
        )?)?)
    }

    pub async fn upload_social_media_link(&self, social_media_link: &str) -> Result<UploadResult> {
        // Check if the link is valid
        is_valid_url(social_media_link)?;

        // Post to the social media endpoint.
        let response: BaseResponse = self
            .post(
                SOCIAL_MEDIA,
                &UploadSocialMediaOptions {
                    social_link: social_media_link.to_string(),
                },
            )
            .await?;

        // Convert to the requested type
        Ok(UploadResult {
            request_id: response.request_id.unwrap(),
            media_id: None,
            result_url: None,
        })
    }

    /// Handle API responses and parse JSON
    async fn handle_response<T: DeserializeOwned>(&self, response: Response) -> Result<T> {
        let status = response.status();
        let body = response.bytes().await?;

        if status == StatusCode::OK || status == StatusCode::CREATED {
            return Ok(serde_json::from_slice(&body)?);
        }

        let response: BaseResponse =
            if let Ok(base_response) = serde_json::from_slice::<BaseResponse>(&body) {
                base_response
            } else {
                BaseResponse {
                    code: "UNKNOWN".to_string(),
                    response: format!("Unknown error (HTTP {status})"),
                    errno: -1,
                    ..Default::default()
                }
            };

        match status {
            StatusCode::BAD_REQUEST => {
                if response.code == "free-tier-not-allowed"
                    || response.code == "upload-limit-reached"
                {
                    Err(Error::Unauthorized(response.response))
                } else {
                    Err(Error::InvalidRequest(response.response))
                }
            }
            StatusCode::UNAUTHORIZED => Err(Error::Unauthorized("Invalid API key".to_string())),
            StatusCode::NOT_FOUND => Err(Error::NotFound),
            _ => Err(Error::ServerError(response.response)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Client, UploadOptions};
    use mockito::Matcher;
    use serde_json::json;
    use std::fs::File;
    use std::io::Write;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_client_new() {
        // Valid configuration
        let config = Config {
            api_key: "test_api_key".to_string(),
            ..Default::default()
        };
        let client = Client::new(config);
        assert!(client.is_ok());

        // Invalid configuration (empty API key)
        let invalid_config = Config {
            api_key: "".to_string(),
            ..Default::default()
        };
        let client = Client::new(invalid_config);
        assert!(client.is_err());
    }

    #[tokio::test]
    async fn test_client_with_custom_url() {
        let server = mockito::Server::new_async().await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };

        let client = Client::new(config);
        assert!(client.is_ok());
        // Cannot directly test get_base_url as it's private to the client
    }

    #[tokio::test]
    async fn test_api_error_handling() {
        let mut server = mockito::Server::new_async().await;

        // Setup mock server for unauthorized error
        let _m = server
            .mock("GET", "/api/media/users/test-request")
            .with_status(401)
            .with_header("content-type", "application/json")
            .with_body(r#"{"response": "Unauthorized access"}"#)
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "invalid_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Make request that should result in error
        let result = client.get_result("test-request", None).await;

        // Verify error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Unauthorized(..) => {} // Expected error
            err => panic!("Unexpected error: {:?}", err),
        }

        // Setup mock server for not found error
        let _m = server
            .mock("GET", "/api/media/users/not-found")
            .with_status(404)
            .with_header("content-type", "application/json")
            .with_body(r#"{"response": "Resource not found"}"#)
            .create_async()
            .await;

        // Make request that should result in not found error
        let result = client.get_result("not-found", None).await;

        // Verify error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::NotFound => {} // Expected error
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_file_flow() {
        let mut server = mockito::Server::new_async().await;
        println!("Server URL: {}", server.url());

        // Create a temporary file for testing
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.jpg");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"test image data").unwrap();
        println!("Created test file at: {:?}", file_path);

        // Mock the presigned URL request
        let _m1 = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(200)
            .with_header("content-type", "application/json")
            .match_header("X-API-KEY", "test_api_key")
            .match_body(Matcher::Json(json!({"fileName": "test.jpg"})))
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "requestId": "test-request-id",
                    "mediaId": "test-media-id",
                    "response": {
                        "signedUrl": format!("{}/upload", server.url())
                    }
                })
                .to_string(),
            )
            .create_async()
            .await;
        println!("Mocked presigned URL endpoint");

        // Mock the upload endpoint
        let _m2 = server
            .mock("PUT", "/upload")
            .with_status(200)
            .match_header("content-type", "image/jpeg")
            .create_async()
            .await;
        println!("Mocked upload endpoint");

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();
        println!("Created client");

        // Upload file
        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        // Print detailed error if test fails
        if let Err(ref e) = result {
            println!("Upload failed with error: {:?}", e);
        }

        // Verify result
        assert!(result.is_ok(), "Upload failed: {:?}", result.err());
        let upload_result = result.unwrap();
        assert_eq!(upload_result.request_id, "test-request-id");
        assert_eq!(upload_result.media_id.unwrap(), "test-media-id");
        assert!(upload_result.result_url.is_none());
    }

    #[tokio::test]
    async fn test_http_post_request() {
        let mut server = mockito::Server::new_async().await;

        // Setup mock server for POST request
        let _m = server
            .mock("POST", "/api/test-endpoint")
            .with_status(200)
            .with_header("content-type", "application/json")
            .match_header("X-API-KEY", "test_api_key")
            .match_header("Content-Type", "application/json")
            .match_body(Matcher::Json(json!({"key": "value"})))
            .with_body(r#"{"status": "success", "message": "Test completed"}"#)
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Access the HTTP client's post method indirectly through client
        // We can test this through the get_result or upload methods
        let _test_data = json!({"key": "value"});

        // Use the client through a method that makes a POST request
        let mock_endpoint = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(200)
            .with_header("content-type", "application/json")
            .match_body(Matcher::Json(json!({"fileName": "test.jpg"})))
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "requestId": "test-request-id",
                    "mediaId": "test-media-id",
                    "response": {
                        "signedUrl": format!("{}/upload", server.url())
                    }
                })
                .to_string(),
            )
            .create_async()
            .await;

        let mock_upload = server
            .mock("PUT", "/upload")
            .with_status(200)
            .create_async()
            .await;

        // Create a temporary file for testing
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.jpg");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"test image data").unwrap();

        // Upload file to test POST request
        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        assert!(result.is_ok());
        mock_endpoint.assert_async().await;
        mock_upload.assert_async().await;
    }

    #[tokio::test]
    async fn test_server_error_handling() {
        let mut server = mockito::Server::new_async().await;

        // Setup mock server for server error
        let _m = server
            .mock("GET", "/api/media/users/test-server-error")
            .with_status(500)
            .with_header("content-type", "application/json")
            .with_body(r#"{"error": "Internal server error"}"#)
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Make request that should result in server error
        let result = client.get_result("test-server-error", None).await;

        // Verify error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::ServerError(_) => {} // Expected error
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_forbidden_error_handling() {
        let mut server = mockito::Server::new_async().await;

        // Setup mock server for forbidden error
        let _m = server
            .mock("GET", "/api/media/users/test-forbidden")
            .with_status(403)
            .with_header("content-type", "application/json")
            .with_body(r#"{"response": "Forbidden access"}"#)
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Make request that should result in forbidden error
        let result = client.get_result("test-forbidden", None).await;

        // Verify error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::ServerError(..) => {} // Expected error (403 maps to Unauthorized)
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_unknown_error_handling() {
        let mut server = mockito::Server::new_async().await;

        // Setup mock server for unknown error with parseable error message
        let _m = server
            .mock("GET", "/api/media/users/test-unknown-error")
            .with_status(400)
            .with_header("content-type", "application/json")
            .with_body(r#"{"code": "custom-code", "errno": 0, "response": "Custom error message", "some": "other-data"}"#)
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Make request that should result in unknown error
        let result = client.get_result("test-unknown-error", None).await;

        // Verify error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidRequest(msg) => {
                assert_eq!(msg, "Custom error message");
            }
            err => panic!("Unexpected error: {:?}", err),
        }

        // Setup mock server for unknown error with unparseable response
        let _m2 = server
            .mock("GET", "/api/media/users/test-unknown-error-2")
            .with_status(422)
            .with_header("content-type", "text/plain")
            .with_body("Unparseable error")
            .create_async()
            .await;

        // Make request that should result in unknown error with unparseable body
        let result = client.get_result("test-unknown-error-2", None).await;

        // Verify error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::ServerError(msg) => {
                assert_eq!(msg, "Unknown error (HTTP 422 Unprocessable Entity)");
            }
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_with_empty_file() {
        let mut server = mockito::Server::new_async().await;

        // Create a temporary empty file for testing
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("empty.jpg");
        File::create(&file_path).unwrap(); // Create empty file

        // Mock the presigned URL request
        let _m = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "requestId": "test-request-id",
                    "mediaId": "test-media-id",
                    "response": {
                        "signedUrl": format!("{}/upload", server.url())
                    }
                })
                .to_string(),
            )
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Upload empty file
        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        // Should fail with InvalidFile error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidFile(_) => {} // Expected error
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_failure() {
        let mut server = mockito::Server::new_async().await;

        // Create a temporary file for testing
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.jpg");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"test image data").unwrap();

        // Mock the presigned URL request
        let _m1 = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "requestId": "test-request-id",
                    "mediaId": "test-media-id",
                    "response": {
                        "signedUrl": format!("{}/upload-fail", server.url())
                    }
                })
                .to_string(),
            )
            .create_async()
            .await;

        // Mock the upload endpoint with failure
        let _m2 = server
            .mock("PUT", "/upload-fail")
            .with_status(400)
            .with_body("Upload failed")
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Upload file that should fail
        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        // Should fail with UploadFailed error
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::UploadFailed(_) => {} // Expected error
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_file_content_type_detection() {
        let mut server = mockito::Server::new_async().await;

        // Create a temporary test file
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.jpg");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"test image data").unwrap();

        // Mock the presigned URL request
        let _m1 = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "requestId": "test-request-id",
                    "mediaId": "test-media-id",
                    "response": {
                        "signedUrl": format!("{}/upload-test", server.url())
                    }
                })
                .to_string(),
            )
            .create_async()
            .await;

        // Mock the upload endpoint - verify it's a JPEG
        let _m2 = server
            .mock("PUT", "/upload-test")
            .match_header("Content-Type", "image/jpeg")
            .with_status(200)
            .create_async()
            .await;

        // Create client with mock server URL
        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Upload JPEG file
        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        // Should succeed
        assert!(
            result.is_ok(),
            "Failed to upload JPEG file: {:?}",
            result.err()
        );

        // Now test a PNG file
        let png_path = dir.path().join("test.png");
        let mut png_file = File::create(&png_path).unwrap();
        png_file.write_all(b"test png data").unwrap();

        // Mock for PNG
        let _m3 = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "requestId": "test-png-id",
                    "mediaId": "test-png-media",
                    "response": {
                        "signedUrl": format!("{}/upload-png", server.url())
                    }
                })
                .to_string(),
            )
            .create_async()
            .await;

        // Mock the upload endpoint for PNG
        let _m4 = server
            .mock("PUT", "/upload-png")
            .match_header("Content-Type", "image/png")
            .with_status(200)
            .create_async()
            .await;

        // Upload PNG file
        let result = client
            .upload(UploadOptions {
                file_path: png_path.to_str().unwrap().to_string(),
            })
            .await;

        // Should succeed
        assert!(
            result.is_ok(),
            "Failed to upload PNG file: {:?}",
            result.err()
        );
    }

    #[tokio::test]
    async fn test_unsupported_file_extension() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.xyz");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"test data").unwrap();

        let config = Config {
            api_key: "test_api_key".to_string(),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidFile(msg) => assert!(msg.contains("Unsupported file type")),
            err => panic!("Expected InvalidFile error, got: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_file_size_exceeds_limit() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("large.jpg");
        let mut file = File::create(&file_path).unwrap();

        // Create a file larger than 50MB (image limit)
        let large_data = vec![0u8; 52428801]; // 50MB + 1 byte
        file.write_all(&large_data).unwrap();

        let config = Config {
            api_key: "test_api_key".to_string(),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidFile(msg) => assert!(msg.contains("File too large")),
            err => panic!("Expected InvalidFile error, got: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_supported_file_extension_within_limit() {
        let mut server = mockito::Server::new_async().await;
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("small.jpg");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"small image").unwrap();

        // Mock presigned URL and upload
        let _m1 = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "requestId": "test-id",
                    "mediaId": "test-media",
                    "response": {"signedUrl": format!("{}/upload", server.url())}
                })
                .to_string(),
            )
            .create_async()
            .await;

        let _m2 = server
            .mock("PUT", "/upload")
            .with_status(200)
            .create_async()
            .await;

        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_file_without_extension() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("no_extension");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"test data").unwrap();

        let config = Config {
            api_key: "test_api_key".to_string(),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidFile(msg) => assert!(msg.contains("Invalid file name")),
            err => panic!("Expected InvalidFile error, got: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_social_media_link_success() {
        let mut server = mockito::Server::new_async().await;

        // Mock the social media upload endpoint
        let _m = server
            .mock("POST", "/api/files/social")
            .with_status(200)
            .with_header("content-type", "application/json")
            .match_header("X-API-KEY", "test_api_key")
            .match_body(Matcher::Json(json!({
                "socialLink": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
            })))
            .with_body(
                json!({
                    "code": "success",
                    "errno": 0,
                    "response": "",
                    "requestId": "social-request-id",
                })
                .to_string(),
            )
            .create_async()
            .await;

        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client
            .upload_social_media("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
            .await;

        println!("{:?}", result);
        assert!(result.is_ok());
        let upload_result = result.unwrap();
        assert_eq!(upload_result.request_id, "social-request-id");
    }

    #[tokio::test]
    async fn test_upload_social_media_link_invalid_url() {
        let config = Config {
            api_key: "test_api_key".to_string(),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Test with invalid URL (no scheme)
        let result = client.upload_social_media("www.example.com").await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidRequest(msg) => {
                assert!(msg.contains("Invalid URL"));
            }
            err => panic!("Expected InvalidRequest error, got: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_social_media_link_invalid_scheme() {
        let config = Config {
            api_key: "test_api_key".to_string(),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Test with invalid scheme
        let result = client.upload_social_media("ftp://example.com/video").await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidRequest(msg) => {
                assert!(msg.contains("http or https scheme"));
            }
            err => panic!("Expected InvalidRequest error, got: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_social_media_link_ip_address() {
        let config = Config {
            api_key: "test_api_key".to_string(),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        // Test with IP address (not allowed)
        let result = client
            .upload_social_media("https://192.168.1.1/video")
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidRequest(msg) => {
                assert!(msg.contains("valid domain"));
            }
            err => panic!("Expected InvalidRequest error, got: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_social_media_link_server_error() {
        let mut server = mockito::Server::new_async().await;

        // Mock server error response
        let _m = server
            .mock("POST", "/api/files/social")
            .with_status(500)
            .with_header("content-type", "application/json")
            .with_body(r#"{"response": "Internal server error"}"#)
            .create_async()
            .await;

        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client
            .upload_social_media("https://www.instagram.com/p/ABC123/")
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::ServerError(_) => {} // Expected error
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_bad_request_error_handling() {
        let mut server = mockito::Server::new_async().await;

        let _m = server
            .mock("GET", "/api/media/users/test-bad-request")
            .with_status(400)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"code": "error", "errno": 400, "response": "Invalid request parameters"}"#,
            )
            .create_async()
            .await;

        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client.get_result("test-bad-request", None).await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidRequest(_) => {} // Expected error
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_upload_bad_request_error() {
        let mut server = mockito::Server::new_async().await;

        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.jpg");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"test data").unwrap();

        let _m = server
            .mock("POST", "/api/files/aws-presigned")
            .with_status(400)
            .with_header("content-type", "application/json")
            .with_body(r#"{"code": "error", "errno": 400, "response": "Invalid file format"}"#)
            .create_async()
            .await;

        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client
            .upload(UploadOptions {
                file_path: file_path.to_str().unwrap().to_string(),
            })
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::InvalidRequest(_) | Error::UploadFailed(_) => {} // Either is acceptable
            err => panic!("Unexpected error: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_free_tier_not_allowed_error() {
        let mut server = mockito::Server::new_async().await;

        let _m = server
            .mock("GET", "/api/media/users/test-free-tier")
            .with_status(400)
            .with_header("content-type", "application/json")
            .with_body(r#"{"code": "free-tier-not-allowed", "errno": 400, "response": "This feature is not available in the free tier"}"#)
            .create_async()
            .await;

        let config = Config {
            api_key: "test_api_key".to_string(),
            base_url: Some(server.url()),
            ..Default::default()
        };
        let client = Client::new(config).unwrap();

        let result = client.get_result("test-free-tier", None).await;

        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Unauthorized(_) => {} // Expected - free tier restrictions are auth-related
            err => panic!("Unexpected error: {:?}", err),
        }
    }
}