arcgis 0.1.3

Type-safe Rust SDK for the ArcGIS REST API with compile-time guarantees
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
//! 📎 Feature Attachments - Manage Files on GIS Features
//!
//! Demonstrates managing file attachments on feature service features.
//! Learn how to upload photos/documents, list attachments, download files,
//! and clean up outdated attachments - perfect for field data collection!
//!
//! # What You'll Learn
//!
//! - **Upload attachments**: Add photos and documents to features
//! - **List attachments**: Query attachment metadata
//! - **Download attachments**: Retrieve files to disk or memory
//! - **Update attachments**: Replace existing files
//! - **Delete attachments**: Remove outdated files
//! - **Binary handling**: Work with images, PDFs, and other file types
//! - **Streaming**: Efficient handling of large files
//!
//! # Prerequisites
//!
//! ## Configure Environment Variables
//!
//! Set these in your `.env` file:
//!
//! ```env
//! # API keys for different privilege levels
//! ARCGIS_CONTENT_KEY=key_with_content_create_privileges    # For creating/deleting services
//! ARCGIS_FEATURES_KEY=key_with_feature_edit_privileges      # For editing features
//! ```
//!
//! ## How This Example Works
//!
//! This example is fully automated - zero manual setup required:
//! 1. **Creates** a hosted feature service with attachments enabled (ARCGIS_CONTENT_KEY)
//! 2. **Adds** layer definition with proper attachment configuration (ARCGIS_CONTENT_KEY)
//! 3. **Creates** a test feature (ARCGIS_FEATURES_KEY)
//! 4. **Demonstrates** all attachment operations (ARCGIS_FEATURES_KEY)
//! 5. **Deletes** the test feature (ARCGIS_FEATURES_KEY)
//! 6. **Deletes** the entire service (ARCGIS_CONTENT_KEY)
//!
//! Run it multiple times - it creates and cleans up everything each time!
//!
//! # Running
//!
//! ```bash
//! cargo run --example feature_attachments
//!
//! # With debug logging:
//! RUST_LOG=debug cargo run --example feature_attachments
//! ```
//!
//! # Real-World Use Case
//!
//! Field workers use mobile devices to collect infrastructure inspection data:
//! - Utility inspector photographs damaged equipment
//! - Photos are automatically attached to the asset feature
//! - Office staff downloads attachments for reports
//! - Old/duplicate attachments are cleaned up periodically

use anyhow::{Context, Result};
use arcgis::example_tracker::ExampleTracker;
use arcgis::{
    ApiKeyAuth, ArcGISClient, ArcGISGeometry, ArcGISPoint, AttachmentId, AttachmentSource,
    CreateServiceParams, DownloadTarget, EditOptions, EnvConfig, Feature, FeatureServiceClient,
    ObjectId, PortalClient,
};
use secrecy::ExposeSecret;
use std::collections::HashMap;

/// Service information needed throughout the example.
struct ServiceInfo {
    service_item_id: String,
    service_url: String,
}

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize tracing for structured logging
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    // Start accountability tracking
    let tracker = ExampleTracker::new("feature_attachments")
        .service_type("ExampleClient")
        .start();

    tracing::info!("📎 ArcGIS Feature Attachments Examples");
    tracing::info!("Demonstrating file attachment management workflows");

    // Load environment configuration (automatically loads .env)
    let config = EnvConfig::global();

    // Validate required keys are present
    let content_key = config.arcgis_content_key.as_ref().context(
        "ARCGIS_CONTENT_KEY not set. Add to .env:\n\
         ARCGIS_CONTENT_KEY=your_api_key_here\n\
         \n\
         This key is used to create and delete services.",
    )?;

    let features_key = config.arcgis_features_key.as_ref().context(
        "ARCGIS_FEATURES_KEY not set. Add to .env:\n\
         ARCGIS_FEATURES_KEY=your_api_key_here\n\
         \n\
         This key is used to create/edit features and attachments.",
    )?;

    // Step 1: Create feature service with attachments enabled
    let service_info = create_feature_service(content_key.expose_secret()).await?;

    // Step 2: Create clients for feature operations
    let features_auth = ApiKeyAuth::new(features_key.expose_secret());
    let features_client = ArcGISClient::new(features_auth);
    let feature_service = FeatureServiceClient::new(&service_info.service_url, &features_client);
    let layer_id = arcgis::LayerId::new(0);

    // Step 3: Create test feature
    let object_id = create_test_feature(&feature_service, layer_id).await?;

    // Step 4: Demonstrate attachment operations
    demonstrate_list_attachments(&feature_service, layer_id, object_id).await?;
    demonstrate_add_photo(&feature_service, layer_id, object_id).await?;
    demonstrate_add_pdf(&feature_service, layer_id, object_id).await?;
    demonstrate_download(&feature_service, layer_id, object_id).await?;
    demonstrate_update(&feature_service, layer_id, object_id).await?;
    demonstrate_delete(&feature_service, layer_id, object_id).await?;

    // Step 5: Cleanup
    cleanup(
        content_key.expose_secret(),
        &feature_service,
        layer_id,
        object_id,
        &service_info.service_item_id,
    )
    .await?;

    print_best_practices();

    // Mark tracking as successful
    tracker.success();
    Ok(())
}

/// Creates a hosted feature service with attachments enabled.
async fn create_feature_service(content_key: &str) -> Result<ServiceInfo> {
    tracing::info!("\n=== Step 1: Creating Feature Service ===");
    tracing::info!("Creating hosted feature service with attachments enabled");

    // Create portal client with content management key
    let content_auth = ApiKeyAuth::new(content_key);
    let content_client = ArcGISClient::new(content_auth);
    let portal = PortalClient::new("https://www.arcgis.com/sharing/rest", &content_client);

    // Create unique service name to avoid conflicts
    use std::time::{SystemTime, UNIX_EPOCH};
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let service_name = format!("AttachmentTest_{}", timestamp);

    // Create the empty hosted feature service
    let create_params = CreateServiceParams::new(&service_name)
        .with_description("Temporary service for testing attachments - will be deleted")
        .with_capabilities("Query,Create,Update,Delete,Editing")
        .with_max_record_count(1000);

    let create_result = portal.create_service(create_params).await?;

    let service_item_id = create_result
        .service_item_id()
        .clone()
        .context("Created service should have item ID")?;
    let service_url = create_result
        .service_url()
        .clone()
        .context("Created service should have URL")?;

    // Verify service was created successfully
    assert!(
        !service_item_id.is_empty(),
        "Service item ID should not be empty"
    );
    assert!(!service_url.is_empty(), "Service URL should not be empty");
    assert!(
        service_url.contains("FeatureServer"),
        "Service URL should contain 'FeatureServer', got: {}",
        service_url
    );

    tracing::info!(
        service_item_id = %service_item_id,
        service_url = %service_url,
        "✅ Empty feature service created"
    );

    // Add layer definition to the service using admin endpoint
    tracing::info!("Adding layer with attachments to the service");
    let admin_url = service_url.replace("/rest/services/", "/rest/admin/services/");
    let add_def_url = format!("{}/addToDefinition", admin_url);

    let layer_definition = create_layer_definition_for_add();

    let mut form = reqwest::multipart::Form::new()
        .text("f", "json")
        .text("addToDefinition", layer_definition.to_string());

    // Get token if required
    if let Some(token) = content_client.get_token_if_required().await? {
        form = form.text("token", token);
    }

    let response = content_client
        .http()
        .post(&add_def_url)
        .multipart(form)
        .send()
        .await?;

    let response_text = response.text().await?;
    tracing::debug!(response = %response_text, "addToDefinition response");

    // Parse response to check for errors
    let add_result: serde_json::Value = serde_json::from_str(&response_text)?;
    if let Some(error) = add_result.get("error") {
        anyhow::bail!("Failed to add layer: {}", error);
    }

    tracing::info!("✅ Layer with attachments enabled added to service");

    Ok(ServiceInfo {
        service_item_id,
        service_url,
    })
}

/// Creates a test feature to demonstrate attachment operations.
async fn create_test_feature(
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
) -> Result<ObjectId> {
    tracing::info!("\n=== Step 2: Creating Test Feature ===");
    tracing::info!("Creating a test feature to demonstrate attachments");

    let mut attributes = HashMap::new();
    attributes.insert(
        "Name".to_string(),
        serde_json::json!("Attachment Test Feature"),
    );

    let geometry = ArcGISGeometry::Point(ArcGISPoint::new(-122.4194, 37.7749));

    let test_feature = Feature::new(attributes, Some(geometry));

    let add_result = feature_service
        .add_features(layer_id, vec![test_feature], EditOptions::new())
        .await?;

    // Verify add operation returned results
    assert!(
        !add_result.add_results().is_empty(),
        "add_features should return at least one result"
    );

    let object_id = if let Some(result) = add_result.add_results().first() {
        // Verify feature was added successfully
        assert!(
            *result.success(),
            "Feature creation should succeed, error: {:?}",
            result.error()
        );

        if *result.success() {
            let oid = result
                .object_id()
                .as_ref()
                .copied()
                .context("Added feature should have ObjectID")?;

            // Verify ObjectID is valid (not 0)
            assert!(oid.0 > 0, "ObjectID should be positive, got: {}", oid.0);

            tracing::info!(object_id = oid.0, "✅ Test feature created");
            oid
        } else {
            anyhow::bail!("Failed to create test feature: {:?}", result.error());
        }
    } else {
        anyhow::bail!("No results from add_features operation");
    };

    Ok(object_id)
}

/// Demonstrates listing existing attachments on a feature.
async fn demonstrate_list_attachments(
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
    object_id: ObjectId,
) -> Result<()> {
    tracing::info!("\n=== Example 1: Listing Existing Attachments ===");
    tracing::info!("Query attachments for feature {}", object_id);

    let attachments = feature_service
        .query_attachments(layer_id, object_id)
        .await?;

    // Verify query returns a list (even if empty initially)
    // This is expected to be 0 for a newly created feature
    tracing::info!(
        attachment_count = attachments.len(),
        "Found existing attachments"
    );

    for attachment in &attachments {
        tracing::info!(
            id = attachment.id().0,
            name = attachment.name(),
            size = attachment.size(),
            content_type = attachment.content_type(),
            "Existing attachment"
        );
    }

    Ok(())
}

/// Demonstrates adding a photo attachment.
async fn demonstrate_add_photo(
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
    object_id: ObjectId,
) -> Result<()> {
    tracing::info!("\n=== Example 2: Adding Photo Attachment ===");
    tracing::info!("Upload an inspection photo to the feature");

    // Create a mock JPEG image (minimal valid JPEG header + data)
    let mock_jpeg_data = create_mock_jpeg();
    let source = AttachmentSource::from_bytes("inspection_photo.jpg", mock_jpeg_data.clone());

    let add_result = feature_service
        .add_attachment(layer_id, object_id, source)
        .await?;

    // Verify photo upload succeeded
    assert!(*add_result.success(), "Photo upload should succeed");
    assert!(
        add_result.object_id().is_some(),
        "Upload result should include object_id"
    );

    if *add_result.success() {
        tracing::info!(
            object_id = ?add_result.object_id().as_ref().map(|id| id.0),
            global_id = ?add_result.global_id(),
            "✅ Photo attached successfully"
        );
    } else {
        tracing::warn!("Failed to attach photo");
    }

    tracing::info!("💡 Tip: Use AttachmentSource::from_path() for large files to stream from disk");

    Ok(())
}

/// Demonstrates adding a PDF document attachment.
async fn demonstrate_add_pdf(
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
    object_id: ObjectId,
) -> Result<()> {
    tracing::info!("\n=== Example 3: Adding PDF Document ===");
    tracing::info!("Attach an inspection report document");

    let mock_pdf_data = create_mock_pdf();
    let source = AttachmentSource::from_bytes("inspection_report.pdf", mock_pdf_data.clone());

    let pdf_result = feature_service
        .add_attachment(layer_id, object_id, source)
        .await?;

    // Verify PDF upload succeeded
    assert!(*pdf_result.success(), "PDF upload should succeed");
    assert!(
        pdf_result.object_id().is_some(),
        "Upload result should include object_id"
    );

    if *pdf_result.success() {
        tracing::info!(
            object_id = ?pdf_result.object_id().as_ref().map(|id| id.0),
            global_id = ?pdf_result.global_id(),
            "✅ PDF attached successfully"
        );
    } else {
        tracing::warn!("Failed to attach PDF");
    }

    Ok(())
}

/// Demonstrates downloading attachments to file and memory.
async fn demonstrate_download(
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
    object_id: ObjectId,
) -> Result<()> {
    tracing::info!("\n=== Example 4: Downloading Attachments ===");
    tracing::info!("Retrieve attachment files for reporting");

    // Query current attachments to get IDs
    let attachments = feature_service
        .query_attachments(layer_id, object_id)
        .await?;

    // Verify we now have attachments (we just added 2: photo and PDF)
    assert!(
        !attachments.is_empty(),
        "Should have attachments after adding photo and PDF"
    );
    assert!(
        attachments.len() >= 2,
        "Should have at least 2 attachments, got {}",
        attachments.len()
    );

    if let Some(attachment) = attachments.first() {
        let attachment_id = *attachment.id();

        // Download to file
        let target = DownloadTarget::to_path("/tmp/downloaded_attachment.dat");
        let download_result = feature_service
            .download_attachment(layer_id, object_id, attachment_id, target)
            .await?;

        // Verify download to file succeeded
        assert!(
            download_result.path().is_some(),
            "Download to file should return a path"
        );

        if let Some(path) = download_result.path() {
            tracing::info!(path = ?path, "✅ Downloaded to file");
        }

        // Download to memory
        let target = DownloadTarget::to_bytes();
        let download_result = feature_service
            .download_attachment(layer_id, object_id, attachment_id, target)
            .await?;

        // Verify download to memory succeeded
        assert!(
            download_result.bytes().is_some(),
            "Download to memory should return bytes"
        );

        if let Some(bytes) = download_result.bytes() {
            // Verify we got actual data (not empty)
            assert!(!bytes.is_empty(), "Downloaded bytes should not be empty");

            tracing::info!(
                size = bytes.len(),
                "✅ Downloaded to memory ({} bytes)",
                bytes.len()
            );
        }
    } else {
        tracing::info!("No attachments available to download");
    }

    tracing::info!("💡 Tip: Use to_path() for large files to avoid loading into memory");

    Ok(())
}

/// Demonstrates updating an existing attachment.
async fn demonstrate_update(
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
    object_id: ObjectId,
) -> Result<()> {
    tracing::info!("\n=== Example 5: Updating an Attachment ===");
    tracing::info!("Replace an outdated photo with a new one");

    // Update the first attachment if it exists
    let attachments = feature_service
        .query_attachments(layer_id, object_id)
        .await?;

    if let Some(attachment) = attachments.first() {
        let attachment_id = *attachment.id();

        // Create updated JPEG content
        let updated_jpeg = create_mock_jpeg();
        let source = AttachmentSource::from_bytes("updated_photo.jpg", updated_jpeg);

        let update_result = feature_service
            .update_attachment(layer_id, object_id, attachment_id, source)
            .await?;

        // Verify update succeeded
        assert!(*update_result.success(), "Attachment update should succeed");

        if *update_result.success() {
            tracing::info!(
                attachment_id = attachment.id().0,
                "✅ Attachment updated successfully"
            );
        } else {
            tracing::warn!("Failed to update attachment");
        }
    } else {
        tracing::info!("No attachments available to update");
    }

    Ok(())
}

/// Demonstrates deleting attachments.
async fn demonstrate_delete(
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
    object_id: ObjectId,
) -> Result<()> {
    tracing::info!("\n=== Example 6: Deleting Attachments ===");
    tracing::info!("Clean up test attachments created in this example");

    // Query all current attachments
    let final_attachments = feature_service
        .query_attachments(layer_id, object_id)
        .await?;

    if !final_attachments.is_empty() {
        // Delete attachments we created (filter by name to avoid deleting user's existing data)
        let test_attachment_ids: Vec<AttachmentId> = final_attachments
            .iter()
            .filter(|att| {
                att.name() == "inspection_photo.jpg"
                    || att.name() == "inspection_report.pdf"
                    || att.name() == "updated_photo.jpg"
            })
            .map(|att| *att.id())
            .collect();

        if !test_attachment_ids.is_empty() {
            tracing::info!(
                count = test_attachment_ids.len(),
                "Deleting test attachments"
            );

            let delete_result = feature_service
                .delete_attachments(layer_id, object_id, test_attachment_ids)
                .await?;

            for item in &delete_result.delete_attachment_results {
                if *item.success() {
                    tracing::info!(
                        object_id = item.object_id().0,
                        "✅ Deleted attachment from feature"
                    );
                } else {
                    tracing::warn!(
                        object_id = item.object_id().0,
                        "Failed to delete attachment"
                    );
                }
            }
        } else {
            tracing::info!("No test attachments to clean up");
        }
    } else {
        tracing::info!("No attachments found");
    }

    Ok(())
}

/// Cleans up test data - deletes feature and service.
async fn cleanup(
    content_key: &str,
    feature_service: &FeatureServiceClient<'_>,
    layer_id: arcgis::LayerId,
    object_id: ObjectId,
    service_item_id: &str,
) -> Result<()> {
    // Cleanup Step 1: Delete the test feature
    tracing::info!("\n=== Step 7: Cleanup - Deleting Test Feature ===");

    let delete_result = feature_service
        .delete_features(layer_id, vec![object_id], EditOptions::new())
        .await?;

    // Verify delete operation returned results
    assert!(
        !delete_result.delete_results().is_empty(),
        "delete_features should return at least one result"
    );

    if let Some(result) = delete_result.delete_results().first() {
        // Verify deletion succeeded
        assert!(
            *result.success(),
            "Feature deletion should succeed, error: {:?}",
            result.error()
        );

        if *result.success() {
            tracing::info!(object_id = object_id.0, "✅ Test feature deleted");
        } else {
            tracing::warn!(
                object_id = object_id.0,
                error = ?result.error(),
                "Failed to delete test feature"
            );
        }
    }

    // Cleanup Step 2: Delete the feature service
    tracing::info!("\n=== Step 8: Cleanup - Deleting Feature Service ===");

    let content_auth = ApiKeyAuth::new(content_key);
    let content_client = ArcGISClient::new(content_auth);
    let portal = PortalClient::new("https://www.arcgis.com/sharing/rest", &content_client);

    portal.delete_service(service_item_id).await?;
    tracing::info!(service_item_id = %service_item_id, "✅ Feature service deleted");
    Ok(())
}

/// Prints best practices and tips for working with attachments.
fn print_best_practices() {
    tracing::info!("\n✅ All attachment operations completed successfully!");
    tracing::info!("💡 Attachment Best Practices:");
    tracing::info!("   - Enable attachments when creating hosted feature layers");
    tracing::info!("   - Use descriptive filenames (e.g., 'site_123_north_view.jpg')");
    tracing::info!("   - Compress images before upload to save storage/bandwidth");
    tracing::info!("   - Stream large files using AttachmentSource::from_path()");
    tracing::info!("   - Download to file for large attachments (not to_bytes())");
    tracing::info!("   - Periodically audit and remove duplicate/outdated attachments");
    tracing::info!("   - Consider file size limits (typically 10MB per attachment)");
    tracing::info!("");
    tracing::info!("📋 Supported file types:");
    tracing::info!("   - Images: JPG, PNG, GIF, BMP, TIFF");
    tracing::info!("   - Documents: PDF, DOC, DOCX, XLS, XLSX, TXT");
    tracing::info!("   - Video: MP4, AVI, MOV (check size limits)");
    tracing::info!("   - Other: ZIP, CSV, KML, GPX");
    tracing::info!("");
    tracing::info!("⚠️  Storage considerations:");
    tracing::info!("   - Attachments count toward your ArcGIS storage quota");
    tracing::info!("   - Each attachment typically limited to 10MB");
    tracing::info!("   - Monitor total storage usage in organization settings");
}

/// Creates a minimal valid JPEG file for demonstration purposes.
///
/// This is a tiny 1x1 pixel black JPEG - just enough to be a valid image file.
fn create_mock_jpeg() -> Vec<u8> {
    // Minimal valid JPEG: 1x1 black pixel
    vec![
        0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00,
        0x48, 0x00, 0x48, 0x00, 0x00, 0xFF, 0xDB, 0x00, 0x43, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
        0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00, 0xFF, 0xC4,
        0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xC4, 0x00, 0x14, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xDA, 0x00,
        0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0x7F, 0xFF, 0xD9,
    ]
}

/// Creates a minimal valid PDF file for demonstration purposes.
///
/// This is a tiny PDF containing just the text "Test" - enough to be valid.
fn create_mock_pdf() -> Vec<u8> {
    // Minimal valid PDF with "Test" text
    let pdf = b"%PDF-1.4
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj
3 0 obj
<<
/Type /Page
/Parent 2 0 R
/MediaBox [0 0 612 792]
/Contents 4 0 R
/Resources <<
/Font <<
/F1 <<
/Type /Font
/Subtype /Type1
/BaseFont /Helvetica
>>
>>
>>
>>
endobj
4 0 obj
<<
/Length 44
>>
stream
BT
/F1 12 Tf
100 700 Td
(Test) Tj
ET
endstream
endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000317 00000 n
trailer
<<
/Size 5
/Root 1 0 R
>>
startxref
410
%%EOF
";
    pdf.to_vec()
}

/// Creates a proper layer definition for addToDefinition operation.
///
/// This creates a point layer with attachments enabled, following the ArcGIS REST API spec:
/// - objectIdField is required
/// - hasAttachments must be true
/// - attachmentProperties defines metadata captured with attachments
/// - templates provide editing support
/// - fields define the layer schema
fn create_layer_definition_for_add() -> serde_json::Value {
    serde_json::json!({
        "layers": [{
            "id": 0,
            "name": "AttachmentTestPoints",
            "type": "Feature Layer",
            "description": "Layer for testing attachments",
            "geometryType": "esriGeometryPoint",
            "hasAttachments": true,
            "attachmentProperties": [
                {"name": "name", "isEnabled": true},
                {"name": "size", "isEnabled": true},
                {"name": "contentType", "isEnabled": true},
                {"name": "keywords", "isEnabled": true}
            ],
            "objectIdField": "OBJECTID",
            "globalIdField": "GlobalID",
            "displayField": "Name",
            "fields": [
                {
                    "name": "OBJECTID",
                    "type": "esriFieldTypeOID",
                    "alias": "Object ID",
                    "editable": false,
                    "nullable": false
                },
                {
                    "name": "GlobalID",
                    "type": "esriFieldTypeGlobalID",
                    "alias": "Global ID",
                    "editable": false,
                    "nullable": false
                },
                {
                    "name": "Name",
                    "type": "esriFieldTypeString",
                    "alias": "Name",
                    "length": 256,
                    "editable": true,
                    "nullable": true
                },
                {
                    "name": "Description",
                    "type": "esriFieldTypeString",
                    "alias": "Description",
                    "length": 1024,
                    "editable": true,
                    "nullable": true
                }
            ],
            "templates": [{
                "name": "New Feature",
                "description": "",
                "drawingTool": "esriFeatureEditToolPoint",
                "prototype": {
                    "attributes": {
                        "Name": null,
                        "Description": null
                    }
                }
            }]
        }]
    })
}