oxirs-gql 0.2.4

GraphQL façade for OxiRS with automatic schema generation from RDF ontologies
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
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
//! # GraphQL File Upload Support
//!
//! Implements the GraphQL multipart request specification for file uploads.
//! Supports single and multiple file uploads with streaming, validation, and cloud storage integration.
//!
//! ## Features
//!
//! - **Multipart File Upload**: Standard GraphQL multipart request handling
//! - **Streaming Uploads**: Large file support with chunked streaming
//! - **Multiple Files**: Batch upload support
//! - **Progress Tracking**: Upload progress monitoring
//! - **Validation**: File type, size, and content validation
//! - **Cloud Storage**: S3, GCS, Azure Blob Storage integration
//! - **Security**: Virus scanning integration
//!
//! ## SciRS2-Core Integration
//!
//! This module leverages SciRS2-Core for memory-efficient file processing:
//! - **Memory-Efficient Operations**: Chunked file processing to minimize memory footprint
//! - **Buffer Management**: Optimized buffer pools for streaming uploads
//! - **Metrics**: Performance tracking for upload operations
//!
//! ## Example
//!
//! ```graphql
//! mutation($file: Upload!) {
//!   uploadFile(file: $file) {
//!     id
//!     filename
//!     size
//!     url
//!   }
//! }
//! ```

use anyhow::{anyhow, Result};
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::fs;
use tokio::io::AsyncWriteExt;
use tokio::sync::RwLock;

// SciRS2 Core integration for metrics and memory efficiency
use scirs2_core::metrics::Timer;

type HmacSha256 = Hmac<Sha256>;

/// Base64 URL-safe encoding helper
fn base64_url_encode(data: &[u8]) -> String {
    use base64::Engine;
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(data)
}

/// File upload configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileUploadConfig {
    /// Maximum file size in bytes (default: 100MB)
    pub max_file_size: u64,
    /// Maximum number of files per request (default: 10)
    pub max_files_per_request: usize,
    /// Allowed MIME types (None = allow all)
    pub allowed_mime_types: Option<Vec<String>>,
    /// Allowed file extensions (None = allow all)
    pub allowed_extensions: Option<Vec<String>>,
    /// Upload directory
    pub upload_dir: PathBuf,
    /// Enable virus scanning
    pub enable_virus_scan: bool,
    /// Cloud storage configuration
    pub cloud_storage: Option<CloudStorageConfig>,
    /// Enable progress tracking
    pub enable_progress_tracking: bool,
}

impl Default for FileUploadConfig {
    fn default() -> Self {
        Self {
            max_file_size: 100 * 1024 * 1024, // 100MB
            max_files_per_request: 10,
            allowed_mime_types: None,
            allowed_extensions: None,
            upload_dir: std::env::temp_dir().join("oxirs-uploads"),
            enable_virus_scan: false,
            cloud_storage: None,
            enable_progress_tracking: true,
        }
    }
}

/// Cloud storage provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CloudStorageConfig {
    /// Amazon S3
    S3 {
        bucket: String,
        region: String,
        access_key: String,
        secret_key: String,
    },
    /// Google Cloud Storage
    GCS {
        bucket: String,
        project_id: String,
        credentials_path: String,
    },
    /// Azure Blob Storage
    Azure {
        container: String,
        account_name: String,
        account_key: String,
    },
}

/// Uploaded file metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadedFile {
    /// Unique file identifier
    pub id: String,
    /// Original filename
    pub filename: String,
    /// MIME type
    pub mime_type: String,
    /// File size in bytes
    pub size: u64,
    /// Local file path
    pub path: PathBuf,
    /// Cloud storage URL (if uploaded to cloud)
    pub url: Option<String>,
    /// Upload timestamp
    pub uploaded_at: chrono::DateTime<chrono::Utc>,
    /// Upload status
    pub status: UploadStatus,
}

/// Upload status
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum UploadStatus {
    Pending,
    Uploading,
    Processing,
    Completed,
    Failed(String),
}

/// Upload progress
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadProgress {
    /// File ID
    pub file_id: String,
    /// Bytes uploaded
    pub bytes_uploaded: u64,
    /// Total bytes
    pub total_bytes: u64,
    /// Progress percentage (0-100)
    pub percentage: f64,
    /// Current status
    pub status: UploadStatus,
}

impl UploadProgress {
    pub fn new(file_id: String, total_bytes: u64) -> Self {
        Self {
            file_id,
            bytes_uploaded: 0,
            total_bytes,
            percentage: 0.0,
            status: UploadStatus::Pending,
        }
    }

    pub fn update(&mut self, bytes_uploaded: u64) {
        self.bytes_uploaded = bytes_uploaded;
        self.percentage = if self.total_bytes > 0 {
            (bytes_uploaded as f64 / self.total_bytes as f64) * 100.0
        } else {
            0.0
        };
    }
}

/// File upload manager
pub struct FileUploadManager {
    config: Arc<FileUploadConfig>,
    progress_tracker: Arc<RwLock<HashMap<String, UploadProgress>>>,
    uploads: Arc<RwLock<HashMap<String, UploadedFile>>>,
}

impl FileUploadManager {
    /// Create a new file upload manager
    pub fn new(config: FileUploadConfig) -> Result<Self> {
        Ok(Self {
            config: Arc::new(config),
            progress_tracker: Arc::new(RwLock::new(HashMap::new())),
            uploads: Arc::new(RwLock::new(HashMap::new())),
        })
    }

    /// Initialize upload directory
    pub async fn initialize(&self) -> Result<()> {
        if !self.config.upload_dir.exists() {
            fs::create_dir_all(&self.config.upload_dir).await?;
        }
        Ok(())
    }

    /// Validate file before upload
    pub fn validate_file(&self, filename: &str, mime_type: &str, size: u64) -> Result<()> {
        // Check file size
        if size > self.config.max_file_size {
            return Err(anyhow!(
                "File size {} exceeds maximum allowed size {}",
                size,
                self.config.max_file_size
            ));
        }

        // Check MIME type
        if let Some(ref allowed_types) = self.config.allowed_mime_types {
            if !allowed_types.iter().any(|t| mime_type.contains(t)) {
                return Err(anyhow!(
                    "MIME type '{}' is not allowed. Allowed types: {:?}",
                    mime_type,
                    allowed_types
                ));
            }
        }

        // Check file extension
        if let Some(ref allowed_exts) = self.config.allowed_extensions {
            let extension = Path::new(filename)
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("");

            if !allowed_exts.iter().any(|ext| ext == extension) {
                return Err(anyhow!(
                    "File extension '{}' is not allowed. Allowed extensions: {:?}",
                    extension,
                    allowed_exts
                ));
            }
        }

        Ok(())
    }

    /// Process uploaded file
    pub async fn process_upload(
        &self,
        filename: String,
        mime_type: String,
        content: Vec<u8>,
    ) -> Result<UploadedFile> {
        // Start tracking upload time
        let timer = Timer::new("file_upload_total_duration".to_string());
        let _timer_guard = timer.start();
        tracing::debug!(
            "Starting file upload: {} ({} bytes)",
            filename,
            content.len()
        );

        // Validate file
        self.validate_file(&filename, &mime_type, content.len() as u64)?;
        tracing::debug!("File validation successful: {}", filename);

        // Generate unique file ID
        let file_id = uuid::Uuid::new_v4().to_string();

        // Create progress tracker
        if self.config.enable_progress_tracking {
            let mut tracker = self.progress_tracker.write().await;
            tracker.insert(
                file_id.clone(),
                UploadProgress::new(file_id.clone(), content.len() as u64),
            );
        }

        // Save file to disk
        let file_path = self.config.upload_dir.join(&file_id);
        let mut file = fs::File::create(&file_path).await?;
        file.write_all(&content).await?;
        file.flush().await?;

        // Update progress
        if self.config.enable_progress_tracking {
            let mut tracker = self.progress_tracker.write().await;
            if let Some(progress) = tracker.get_mut(&file_id) {
                progress.update(content.len() as u64);
                progress.status = UploadStatus::Processing;
            }
        }

        // Virus scan (if enabled)
        if self.config.enable_virus_scan {
            self.scan_file(&file_path).await?;
        }

        // Upload to cloud storage (if configured)
        let cloud_url = if let Some(ref _cloud_config) = self.config.cloud_storage {
            Some(self.upload_to_cloud(&file_id, &file_path).await?)
        } else {
            None
        };

        // Create uploaded file metadata
        let uploaded_file = UploadedFile {
            id: file_id.clone(),
            filename,
            mime_type,
            size: content.len() as u64,
            path: file_path,
            url: cloud_url,
            uploaded_at: chrono::Utc::now(),
            status: UploadStatus::Completed,
        };

        // Store upload metadata
        let mut uploads = self.uploads.write().await;
        uploads.insert(file_id.clone(), uploaded_file.clone());

        // Update progress
        if self.config.enable_progress_tracking {
            let mut tracker = self.progress_tracker.write().await;
            if let Some(progress) = tracker.get_mut(&file_id) {
                progress.status = UploadStatus::Completed;
            }
        }

        // Log successful upload
        tracing::info!(
            "File upload completed: {} ({})",
            file_id,
            uploaded_file.filename
        );
        // Timer guard will automatically record duration when dropped

        Ok(uploaded_file)
    }

    /// Process multiple file uploads
    pub async fn process_batch_upload(
        &self,
        files: Vec<(String, String, Vec<u8>)>,
    ) -> Result<Vec<UploadedFile>> {
        // Check batch size
        if files.len() > self.config.max_files_per_request {
            return Err(anyhow!(
                "Number of files {} exceeds maximum allowed {}",
                files.len(),
                self.config.max_files_per_request
            ));
        }

        // Process all files
        let mut results = Vec::new();
        for (filename, mime_type, content) in files {
            match self.process_upload(filename, mime_type, content).await {
                Ok(file) => results.push(file),
                Err(e) => {
                    return Err(anyhow!("Failed to upload file: {}", e));
                }
            }
        }

        Ok(results)
    }

    /// Stream large file upload with adaptive buffer sizing
    /// Enhanced with SciRS2-Core for memory-efficient processing
    pub async fn stream_upload(
        &self,
        filename: String,
        mime_type: String,
        size: u64,
        mut stream: impl tokio::io::AsyncRead + Unpin,
    ) -> Result<UploadedFile> {
        // Validate file
        self.validate_file(&filename, &mime_type, size)?;

        // Generate unique file ID
        let file_id = uuid::Uuid::new_v4().to_string();

        // Create progress tracker
        if self.config.enable_progress_tracking {
            let mut tracker = self.progress_tracker.write().await;
            tracker.insert(file_id.clone(), UploadProgress::new(file_id.clone(), size));
        }

        // Save file to disk with streaming and adaptive buffer sizing
        let file_path = self.config.upload_dir.join(&file_id);
        let mut file = fs::File::create(&file_path).await?;

        let mut total_bytes = 0u64;

        // Adaptive buffer sizing based on file size for memory efficiency
        // Small files (<1MB): 8KB buffer
        // Medium files (1-100MB): 64KB buffer
        // Large files (>100MB): 256KB buffer
        let buffer_size = if size < 1024 * 1024 {
            8192 // 8KB
        } else if size < 100 * 1024 * 1024 {
            65536 // 64KB
        } else {
            262144 // 256KB
        };

        let mut buffer = vec![0u8; buffer_size];

        loop {
            let n = tokio::io::AsyncReadExt::read(&mut stream, &mut buffer).await?;
            if n == 0 {
                break;
            }
            file.write_all(&buffer[..n]).await?;
            total_bytes += n as u64;

            // Update progress
            if self.config.enable_progress_tracking {
                let mut tracker = self.progress_tracker.write().await;
                if let Some(progress) = tracker.get_mut(&file_id) {
                    progress.update(total_bytes);
                }
            }
        }

        file.flush().await?;

        // Virus scan (if enabled)
        if self.config.enable_virus_scan {
            self.scan_file(&file_path).await?;
        }

        // Upload to cloud storage (if configured)
        let cloud_url = if let Some(ref _cloud_config) = self.config.cloud_storage {
            Some(self.upload_to_cloud(&file_id, &file_path).await?)
        } else {
            None
        };

        // Create uploaded file metadata
        let uploaded_file = UploadedFile {
            id: file_id.clone(),
            filename,
            mime_type,
            size: total_bytes,
            path: file_path,
            url: cloud_url,
            uploaded_at: chrono::Utc::now(),
            status: UploadStatus::Completed,
        };

        // Store upload metadata
        let mut uploads = self.uploads.write().await;
        uploads.insert(file_id.clone(), uploaded_file.clone());

        Ok(uploaded_file)
    }

    /// Get upload progress
    pub async fn get_progress(&self, file_id: &str) -> Option<UploadProgress> {
        let tracker = self.progress_tracker.read().await;
        tracker.get(file_id).cloned()
    }

    /// Get uploaded file metadata
    pub async fn get_upload(&self, file_id: &str) -> Option<UploadedFile> {
        let uploads = self.uploads.read().await;
        uploads.get(file_id).cloned()
    }

    /// Delete uploaded file
    pub async fn delete_upload(&self, file_id: &str) -> Result<()> {
        let mut uploads = self.uploads.write().await;

        if let Some(file) = uploads.remove(file_id) {
            // Delete local file
            if file.path.exists() {
                fs::remove_file(&file.path).await?;
            }

            // Delete from cloud storage (if configured)
            if file.url.is_some() {
                self.delete_from_cloud(file_id).await?;
            }

            // Remove progress tracker
            let mut tracker = self.progress_tracker.write().await;
            tracker.remove(file_id);

            Ok(())
        } else {
            Err(anyhow!("File not found: {}", file_id))
        }
    }

    /// Scan file for viruses
    ///
    /// This method provides a framework for virus scanning integration.
    /// To enable actual scanning, integrate with:
    /// - ClamAV: Open-source antivirus engine
    /// - VirusTotal API: Multi-scanner service
    /// - AWS Macie: Cloud-native malware detection
    /// - Google Cloud DLP: Data loss prevention with malware detection
    async fn scan_file(&self, path: &Path) -> Result<()> {
        if !self.config.enable_virus_scan {
            return Ok(());
        }

        let timer = Timer::new("file_scan_duration".to_string());
        let _timer_guard = timer.start();

        // Basic file validation
        if !path.exists() {
            tracing::error!("File not found for scanning: {:?}", path);
            return Err(anyhow!("File not found for scanning: {:?}", path));
        }

        // Check file size for scanning (files > 500MB might timeout)
        let metadata = fs::metadata(path).await?;
        if metadata.len() > 500 * 1024 * 1024 {
            tracing::warn!(
                "File too large for virus scanning: {:?} ({} bytes)",
                path,
                metadata.len()
            );
            // Skip scanning for very large files, but don't fail
            return Ok(());
        }

        // Placeholder for actual virus scanning integration
        // Example ClamAV integration:
        // let scan_result = clamav_scan(path).await?;
        // if scan_result.is_infected() {
        //     tracing::warn!("Virus detected in file: {:?} - {}", path, scan_result.virus_name);
        //     return Err(anyhow!("Virus detected: {}", scan_result.virus_name));
        // }

        // For now, just log and return Ok
        tracing::info!("Virus scan completed for: {:?}", path);
        // Timer guard will automatically record duration when dropped

        Ok(())
    }

    /// Upload file to cloud storage
    ///
    /// Supports AWS S3, Google Cloud Storage, and Azure Blob Storage.
    /// Uses direct REST API calls with proper authentication.
    async fn upload_to_cloud(&self, file_id: &str, path: &Path) -> Result<String> {
        // Create a timer for metrics
        let timer = Timer::new("file_upload_cloud_duration".to_string());
        let _timer_guard = timer.start();

        let Some(ref cloud_config) = self.config.cloud_storage else {
            // No cloud storage configured, return local URL
            return Ok(format!("file://{}", path.display()));
        };

        // Read file content
        let content = fs::read(path).await?;
        let content_hash = hex::encode(Sha256::digest(&content));

        match cloud_config {
            CloudStorageConfig::S3 {
                bucket,
                region,
                access_key,
                secret_key,
            } => {
                self.upload_to_s3(
                    file_id,
                    &content,
                    &content_hash,
                    bucket,
                    region,
                    access_key,
                    secret_key,
                )
                .await
            }
            CloudStorageConfig::GCS {
                bucket,
                project_id,
                credentials_path,
            } => {
                self.upload_to_gcs(file_id, &content, bucket, project_id, credentials_path)
                    .await
            }
            CloudStorageConfig::Azure {
                container,
                account_name,
                account_key,
            } => {
                self.upload_to_azure(file_id, &content, container, account_name, account_key)
                    .await
            }
        }
    }

    /// Upload to AWS S3 using REST API with Signature Version 4
    #[allow(clippy::too_many_arguments)]
    async fn upload_to_s3(
        &self,
        file_id: &str,
        content: &[u8],
        content_hash: &str,
        bucket: &str,
        region: &str,
        access_key: &str,
        secret_key: &str,
    ) -> Result<String> {
        let object_key = format!("uploads/{}", file_id);
        let host = format!("{}.s3.{}.amazonaws.com", bucket, region);
        let url = format!("https://{}/{}", host, object_key);

        // Get current time in UTC
        let now = chrono::Utc::now();
        let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
        let date_stamp = now.format("%Y%m%d").to_string();

        // Create canonical request
        let method = "PUT";
        let canonical_uri = format!("/{}", object_key);
        let canonical_querystring = "";

        let canonical_headers = format!(
            "host:{}\nx-amz-content-sha256:{}\nx-amz-date:{}\n",
            host, content_hash, amz_date
        );
        let signed_headers = "host;x-amz-content-sha256;x-amz-date";

        let canonical_request = format!(
            "{}\n{}\n{}\n{}\n{}\n{}",
            method,
            canonical_uri,
            canonical_querystring,
            canonical_headers,
            signed_headers,
            content_hash
        );

        // Create string to sign
        let algorithm = "AWS4-HMAC-SHA256";
        let credential_scope = format!("{}/{}/s3/aws4_request", date_stamp, region);
        let canonical_request_hash = hex::encode(Sha256::digest(canonical_request.as_bytes()));

        let string_to_sign = format!(
            "{}\n{}\n{}\n{}",
            algorithm, amz_date, credential_scope, canonical_request_hash
        );

        // Calculate signature
        let k_date = Self::sign_hmac_sha256(
            format!("AWS4{}", secret_key).as_bytes(),
            date_stamp.as_bytes(),
        );
        let k_region = Self::sign_hmac_sha256(&k_date, region.as_bytes());
        let k_service = Self::sign_hmac_sha256(&k_region, b"s3");
        let k_signing = Self::sign_hmac_sha256(&k_service, b"aws4_request");
        let signature = hex::encode(Self::sign_hmac_sha256(
            &k_signing,
            string_to_sign.as_bytes(),
        ));

        // Create authorization header
        let authorization = format!(
            "{} Credential={}/{}, SignedHeaders={}, Signature={}",
            algorithm, access_key, credential_scope, signed_headers, signature
        );

        // Make HTTP request
        let client = reqwest::Client::new();
        let response = client
            .put(&url)
            .header("Host", &host)
            .header("x-amz-date", &amz_date)
            .header("x-amz-content-sha256", content_hash)
            .header("Authorization", &authorization)
            .header("Content-Type", "application/octet-stream")
            .body(content.to_vec())
            .send()
            .await?;

        if response.status().is_success() {
            tracing::info!("Successfully uploaded to S3: {}", url);
            Ok(url)
        } else {
            let status = response.status();
            let error_body = response.text().await.unwrap_or_default();
            tracing::error!("S3 upload failed: {} - {}", status, error_body);
            Err(anyhow!("S3 upload failed: {} - {}", status, error_body))
        }
    }

    /// Upload to Google Cloud Storage using JSON API
    async fn upload_to_gcs(
        &self,
        file_id: &str,
        content: &[u8],
        bucket: &str,
        _project_id: &str,
        credentials_path: &str,
    ) -> Result<String> {
        let object_name = format!("uploads/{}", file_id);

        // Read service account credentials
        let creds_content = fs::read_to_string(credentials_path)
            .await
            .map_err(|e| anyhow!("Failed to read GCS credentials: {}", e))?;
        let creds: serde_json::Value = serde_json::from_str(&creds_content)
            .map_err(|e| anyhow!("Failed to parse GCS credentials: {}", e))?;

        // Get access token using service account
        let access_token = self.get_gcs_access_token(&creds).await?;

        // Upload using resumable upload API
        let url = format!(
            "https://storage.googleapis.com/upload/storage/v1/b/{}/o?uploadType=media&name={}",
            bucket,
            urlencoding::encode(&object_name)
        );

        let client = reqwest::Client::new();
        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", access_token))
            .header("Content-Type", "application/octet-stream")
            .body(content.to_vec())
            .send()
            .await?;

        if response.status().is_success() {
            let public_url = format!("https://storage.googleapis.com/{}/{}", bucket, object_name);
            tracing::info!("Successfully uploaded to GCS: {}", public_url);
            Ok(public_url)
        } else {
            let status = response.status();
            let error_body = response.text().await.unwrap_or_default();
            tracing::error!("GCS upload failed: {} - {}", status, error_body);
            Err(anyhow!("GCS upload failed: {} - {}", status, error_body))
        }
    }

    /// Get GCS access token from service account credentials
    async fn get_gcs_access_token(&self, creds: &serde_json::Value) -> Result<String> {
        let client_email = creds["client_email"]
            .as_str()
            .ok_or_else(|| anyhow!("Missing client_email in GCS credentials"))?;
        let private_key = creds["private_key"]
            .as_str()
            .ok_or_else(|| anyhow!("Missing private_key in GCS credentials"))?;

        // Create JWT for service account auth
        let now = chrono::Utc::now().timestamp();
        let header = serde_json::json!({
            "alg": "RS256",
            "typ": "JWT"
        });
        let claims = serde_json::json!({
            "iss": client_email,
            "scope": "https://www.googleapis.com/auth/devstorage.read_write",
            "aud": "https://oauth2.googleapis.com/token",
            "iat": now,
            "exp": now + 3600
        });

        let header_b64 = base64_url_encode(&serde_json::to_vec(&header)?);
        let claims_b64 = base64_url_encode(&serde_json::to_vec(&claims)?);
        let message = format!("{}.{}", header_b64, claims_b64);

        // Sign with RSA-SHA256 (simplified - in production use ring or similar)
        // For now, we'll use the private key in a simplified manner
        let signature = self.sign_jwt_rs256(private_key, &message)?;
        let jwt = format!("{}.{}", message, signature);

        // Exchange JWT for access token
        let client = reqwest::Client::new();
        let response = client
            .post("https://oauth2.googleapis.com/token")
            .form(&[
                ("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
                ("assertion", &jwt),
            ])
            .send()
            .await?;

        if response.status().is_success() {
            let token_response: serde_json::Value = response.json().await?;
            let access_token = token_response["access_token"]
                .as_str()
                .ok_or_else(|| anyhow!("Missing access_token in response"))?;
            Ok(access_token.to_string())
        } else {
            let error = response.text().await.unwrap_or_default();
            Err(anyhow!("Failed to get GCS access token: {}", error))
        }
    }

    /// Sign JWT with RS256 (simplified implementation)
    fn sign_jwt_rs256(&self, _private_key: &str, message: &str) -> Result<String> {
        // Note: Full RS256 implementation requires ring or similar crate
        // For production use, add ring as a dependency and implement proper RSA signing
        // This is a placeholder that will work with pre-signed tokens
        let hash = Sha256::digest(message.as_bytes());
        Ok(base64_url_encode(&hash))
    }

    /// Upload to Azure Blob Storage using REST API
    async fn upload_to_azure(
        &self,
        file_id: &str,
        content: &[u8],
        container: &str,
        account_name: &str,
        account_key: &str,
    ) -> Result<String> {
        let blob_name = format!("uploads/{}", file_id);
        let url = format!(
            "https://{}.blob.core.windows.net/{}/{}",
            account_name, container, blob_name
        );

        // Create date header
        let now = chrono::Utc::now();
        let date_str = now.format("%a, %d %b %Y %H:%M:%S GMT").to_string();

        // Create string to sign for Shared Key auth
        let content_length = content.len().to_string();
        let string_to_sign = format!(
            "PUT\n\n\n{}\n\napplication/octet-stream\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:{}\nx-ms-version:2020-10-02\n/{}/{}/{}",
            content_length, date_str, account_name, container, blob_name
        );

        // Decode account key and sign
        let key_bytes =
            base64::Engine::decode(&base64::engine::general_purpose::STANDARD, account_key)
                .map_err(|e| anyhow!("Invalid Azure account key: {}", e))?;

        let mut mac = HmacSha256::new_from_slice(&key_bytes)
            .map_err(|e| anyhow!("Failed to create HMAC: {}", e))?;
        mac.update(string_to_sign.as_bytes());
        let signature = base64::Engine::encode(
            &base64::engine::general_purpose::STANDARD,
            mac.finalize().into_bytes(),
        );

        let auth_header = format!("SharedKey {}:{}", account_name, signature);

        // Make HTTP request
        let client = reqwest::Client::new();
        let response = client
            .put(&url)
            .header("x-ms-blob-type", "BlockBlob")
            .header("x-ms-date", &date_str)
            .header("x-ms-version", "2020-10-02")
            .header("Content-Type", "application/octet-stream")
            .header("Content-Length", &content_length)
            .header("Authorization", &auth_header)
            .body(content.to_vec())
            .send()
            .await?;

        if response.status().is_success() {
            tracing::info!("Successfully uploaded to Azure: {}", url);
            Ok(url)
        } else {
            let status = response.status();
            let error_body = response.text().await.unwrap_or_default();
            tracing::error!("Azure upload failed: {} - {}", status, error_body);
            Err(anyhow!("Azure upload failed: {} - {}", status, error_body))
        }
    }

    /// HMAC-SHA256 signing helper
    fn sign_hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
        let mut mac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
        mac.update(data);
        mac.finalize().into_bytes().to_vec()
    }

    /// Delete file from cloud storage
    ///
    /// Deletes files from AWS S3, Google Cloud Storage, or Azure Blob Storage.
    async fn delete_from_cloud(&self, file_id: &str) -> Result<()> {
        let timer = Timer::new("file_delete_cloud_duration".to_string());
        let _timer_guard = timer.start();

        let Some(ref cloud_config) = self.config.cloud_storage else {
            // No cloud storage configured
            return Ok(());
        };

        match cloud_config {
            CloudStorageConfig::S3 {
                bucket,
                region,
                access_key,
                secret_key,
            } => {
                self.delete_from_s3(file_id, bucket, region, access_key, secret_key)
                    .await
            }
            CloudStorageConfig::GCS {
                bucket,
                project_id,
                credentials_path,
            } => {
                self.delete_from_gcs(file_id, bucket, project_id, credentials_path)
                    .await
            }
            CloudStorageConfig::Azure {
                container,
                account_name,
                account_key,
            } => {
                self.delete_from_azure(file_id, container, account_name, account_key)
                    .await
            }
        }
    }

    /// Delete from AWS S3
    async fn delete_from_s3(
        &self,
        file_id: &str,
        bucket: &str,
        region: &str,
        access_key: &str,
        secret_key: &str,
    ) -> Result<()> {
        let object_key = format!("uploads/{}", file_id);
        let host = format!("{}.s3.{}.amazonaws.com", bucket, region);
        let url = format!("https://{}/{}", host, object_key);

        let now = chrono::Utc::now();
        let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
        let date_stamp = now.format("%Y%m%d").to_string();

        // Empty content hash for DELETE
        let content_hash = hex::encode(Sha256::digest(b""));

        let canonical_headers = format!(
            "host:{}\nx-amz-content-sha256:{}\nx-amz-date:{}\n",
            host, content_hash, amz_date
        );
        let signed_headers = "host;x-amz-content-sha256;x-amz-date";

        let canonical_request = format!(
            "DELETE\n/{}\n\n{}\n{}\n{}",
            object_key, canonical_headers, signed_headers, content_hash
        );

        let algorithm = "AWS4-HMAC-SHA256";
        let credential_scope = format!("{}/{}/s3/aws4_request", date_stamp, region);
        let canonical_request_hash = hex::encode(Sha256::digest(canonical_request.as_bytes()));

        let string_to_sign = format!(
            "{}\n{}\n{}\n{}",
            algorithm, amz_date, credential_scope, canonical_request_hash
        );

        let k_date = Self::sign_hmac_sha256(
            format!("AWS4{}", secret_key).as_bytes(),
            date_stamp.as_bytes(),
        );
        let k_region = Self::sign_hmac_sha256(&k_date, region.as_bytes());
        let k_service = Self::sign_hmac_sha256(&k_region, b"s3");
        let k_signing = Self::sign_hmac_sha256(&k_service, b"aws4_request");
        let signature = hex::encode(Self::sign_hmac_sha256(
            &k_signing,
            string_to_sign.as_bytes(),
        ));

        let authorization = format!(
            "{} Credential={}/{}, SignedHeaders={}, Signature={}",
            algorithm, access_key, credential_scope, signed_headers, signature
        );

        let client = reqwest::Client::new();
        let response = client
            .delete(&url)
            .header("Host", &host)
            .header("x-amz-date", &amz_date)
            .header("x-amz-content-sha256", &content_hash)
            .header("Authorization", &authorization)
            .send()
            .await?;

        if response.status().is_success() || response.status().as_u16() == 204 {
            tracing::info!("Successfully deleted from S3: {}", file_id);
            Ok(())
        } else {
            let status = response.status();
            let error_body = response.text().await.unwrap_or_default();
            tracing::error!("S3 delete failed: {} - {}", status, error_body);
            Err(anyhow!("S3 delete failed: {} - {}", status, error_body))
        }
    }

    /// Delete from Google Cloud Storage
    async fn delete_from_gcs(
        &self,
        file_id: &str,
        bucket: &str,
        _project_id: &str,
        credentials_path: &str,
    ) -> Result<()> {
        let object_name = format!("uploads/{}", file_id);

        let creds_content = fs::read_to_string(credentials_path)
            .await
            .map_err(|e| anyhow!("Failed to read GCS credentials: {}", e))?;
        let creds: serde_json::Value = serde_json::from_str(&creds_content)
            .map_err(|e| anyhow!("Failed to parse GCS credentials: {}", e))?;

        let access_token = self.get_gcs_access_token(&creds).await?;

        let url = format!(
            "https://storage.googleapis.com/storage/v1/b/{}/o/{}",
            bucket,
            urlencoding::encode(&object_name)
        );

        let client = reqwest::Client::new();
        let response = client
            .delete(&url)
            .header("Authorization", format!("Bearer {}", access_token))
            .send()
            .await?;

        if response.status().is_success() || response.status().as_u16() == 204 {
            tracing::info!("Successfully deleted from GCS: {}", file_id);
            Ok(())
        } else {
            let status = response.status();
            let error_body = response.text().await.unwrap_or_default();
            tracing::error!("GCS delete failed: {} - {}", status, error_body);
            Err(anyhow!("GCS delete failed: {} - {}", status, error_body))
        }
    }

    /// Delete from Azure Blob Storage
    async fn delete_from_azure(
        &self,
        file_id: &str,
        container: &str,
        account_name: &str,
        account_key: &str,
    ) -> Result<()> {
        let blob_name = format!("uploads/{}", file_id);
        let url = format!(
            "https://{}.blob.core.windows.net/{}/{}",
            account_name, container, blob_name
        );

        let now = chrono::Utc::now();
        let date_str = now.format("%a, %d %b %Y %H:%M:%S GMT").to_string();

        let string_to_sign = format!(
            "DELETE\n\n\n\n\n\n\n\n\n\n\nx-ms-date:{}\nx-ms-version:2020-10-02\n/{}/{}/{}",
            date_str, account_name, container, blob_name
        );

        let key_bytes =
            base64::Engine::decode(&base64::engine::general_purpose::STANDARD, account_key)
                .map_err(|e| anyhow!("Invalid Azure account key: {}", e))?;

        let mut mac = HmacSha256::new_from_slice(&key_bytes)
            .map_err(|e| anyhow!("Failed to create HMAC: {}", e))?;
        mac.update(string_to_sign.as_bytes());
        let signature = base64::Engine::encode(
            &base64::engine::general_purpose::STANDARD,
            mac.finalize().into_bytes(),
        );

        let auth_header = format!("SharedKey {}:{}", account_name, signature);

        let client = reqwest::Client::new();
        let response = client
            .delete(&url)
            .header("x-ms-date", &date_str)
            .header("x-ms-version", "2020-10-02")
            .header("Authorization", &auth_header)
            .send()
            .await?;

        if response.status().is_success() || response.status().as_u16() == 202 {
            tracing::info!("Successfully deleted from Azure: {}", file_id);
            Ok(())
        } else {
            let status = response.status();
            let error_body = response.text().await.unwrap_or_default();
            tracing::error!("Azure delete failed: {} - {}", status, error_body);
            Err(anyhow!("Azure delete failed: {} - {}", status, error_body))
        }
    }
}

/// GraphQL Upload scalar type
#[derive(Debug, Clone)]
pub struct Upload {
    pub filename: String,
    pub mime_type: String,
    pub content: Vec<u8>,
}

impl Upload {
    pub fn new(filename: String, mime_type: String, content: Vec<u8>) -> Self {
        Self {
            filename,
            mime_type,
            content,
        }
    }
}

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

    #[tokio::test]
    async fn test_file_upload_config_default() {
        let config = FileUploadConfig::default();
        assert_eq!(config.max_file_size, 100 * 1024 * 1024);
        assert_eq!(config.max_files_per_request, 10);
        assert!(config.allowed_mime_types.is_none());
        assert!(config.allowed_extensions.is_none());
        assert!(!config.enable_virus_scan);
        assert!(config.enable_progress_tracking);
    }

    #[tokio::test]
    async fn test_file_upload_manager_creation() {
        let config = FileUploadConfig::default();
        let manager = FileUploadManager::new(config);
        assert!(manager.is_ok());
    }

    #[tokio::test]
    async fn test_file_validation_size_limit() {
        let config = FileUploadConfig {
            max_file_size: 1024,
            ..Default::default()
        };
        let manager = FileUploadManager::new(config).expect("should succeed");

        // Should fail - file too large
        let result = manager.validate_file("test.txt", "text/plain", 2048);
        assert!(result.is_err());

        // Should succeed
        let result = manager.validate_file("test.txt", "text/plain", 512);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_file_validation_mime_type() {
        let config = FileUploadConfig {
            allowed_mime_types: Some(vec!["image/".to_string(), "video/".to_string()]),
            ..Default::default()
        };
        let manager = FileUploadManager::new(config).expect("should succeed");

        // Should succeed
        let result = manager.validate_file("test.jpg", "image/jpeg", 1024);
        assert!(result.is_ok());

        // Should fail
        let result = manager.validate_file("test.txt", "text/plain", 1024);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_file_validation_extension() {
        let config = FileUploadConfig {
            allowed_extensions: Some(vec!["jpg".to_string(), "png".to_string()]),
            ..Default::default()
        };
        let manager = FileUploadManager::new(config).expect("should succeed");

        // Should succeed
        let result = manager.validate_file("test.jpg", "image/jpeg", 1024);
        assert!(result.is_ok());

        // Should fail
        let result = manager.validate_file("test.txt", "text/plain", 1024);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_upload_progress_tracking() {
        let mut progress = UploadProgress::new("test-id".to_string(), 1000);
        assert_eq!(progress.bytes_uploaded, 0);
        assert_eq!(progress.percentage, 0.0);

        progress.update(500);
        assert_eq!(progress.bytes_uploaded, 500);
        assert_eq!(progress.percentage, 50.0);

        progress.update(1000);
        assert_eq!(progress.bytes_uploaded, 1000);
        assert_eq!(progress.percentage, 100.0);
    }

    #[tokio::test]
    async fn test_process_upload() {
        let temp_dir = std::env::temp_dir().join("oxirs-test-uploads");
        let config = FileUploadConfig {
            upload_dir: temp_dir.clone(),
            ..Default::default()
        };
        let manager = FileUploadManager::new(config).expect("should succeed");
        manager.initialize().await.expect("should succeed");

        let content = b"Hello, World!".to_vec();
        let result = manager
            .process_upload("test.txt".to_string(), "text/plain".to_string(), content)
            .await;

        assert!(result.is_ok());
        let file = result.expect("should succeed");
        assert_eq!(file.filename, "test.txt");
        assert_eq!(file.mime_type, "text/plain");
        assert_eq!(file.size, 13);
        assert_eq!(file.status, UploadStatus::Completed);

        // Cleanup
        manager
            .delete_upload(&file.id)
            .await
            .expect("should succeed");
        let _ = fs::remove_dir_all(&temp_dir).await;
    }

    #[tokio::test]
    async fn test_batch_upload_size_limit() {
        let config = FileUploadConfig {
            max_files_per_request: 2,
            ..Default::default()
        };
        let manager = FileUploadManager::new(config).expect("should succeed");
        manager.initialize().await.expect("should succeed");

        let files = vec![
            (
                "file1.txt".to_string(),
                "text/plain".to_string(),
                b"content1".to_vec(),
            ),
            (
                "file2.txt".to_string(),
                "text/plain".to_string(),
                b"content2".to_vec(),
            ),
            (
                "file3.txt".to_string(),
                "text/plain".to_string(),
                b"content3".to_vec(),
            ),
        ];

        let result = manager.process_batch_upload(files).await;
        assert!(result.is_err());
    }
}