bing-webmaster-api 1.0.2

Rust client for the Bing Webmaster API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
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
//! Data Transfer Objects (DTOs) for Bing Webmaster API
//!
//! This module contains all data structures used for communication with the Bing Webmaster API.
//! All structures mirror the .NET API definitions from `Microsoft.Bing.Webmaster.Api.Interfaces`.
//!
//! # Field Naming
//!
//! All fields use `#[serde(rename = "...")]` to match the PascalCase naming convention
//! used by the .NET API, while providing idiomatic snake_case Rust field names.

use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

/// .NET DateTime serialization format used by Bing API
///
/// The Bing API uses .NET's JSON date format: `/Date(timestamp-offset)/`
/// where timestamp is milliseconds since Unix epoch.
///
/// # Format
/// `/Date(1316156400000-0700)/`
/// - `1316156400000` - milliseconds since Unix epoch
/// - `-0700` - timezone offset (optional)
mod dotnet_date_format {
    use chrono::{DateTime, NaiveDate, TimeZone, Utc};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S>(date: &NaiveDate, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let timestamp_ms = date
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp_millis();
        let formatted = format!("/Date({})/", timestamp_ms);
        formatted.serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<NaiveDate, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;

        // Handle special case: dates starting with /Date(- are considered null
        if s.starts_with("/Date(-") {
            return Err(serde::de::Error::custom("Null date value"));
        }

        // Handle .NET date format: "/Date(1316156400000-0700)/"
        if s.starts_with("/Date(") && s.ends_with(")/") {
            let inner = &s[6..s.len() - 2]; // Remove "/Date(" and ")/"

            // Find last - or + for timezone offset
            let (hyph_pos, is_negative) = if let Some(pos) = inner.rfind('-') {
                (Some(pos), true)
            } else if let Some(pos) = inner.rfind('+') {
                (Some(pos), false)
            } else {
                (None, true)
            };

            if let Some(hyph) = hyph_pos {
                // Parse timestamp before timezone offset
                let timestamp_str = &inner[..hyph];
                let mut timestamp_ms = timestamp_str
                    .parse::<f64>()
                    .map_err(|_| serde::de::Error::custom("Failed to parse timestamp"))?;

                // Parse timezone offset hours (2 digits)
                if hyph + 3 <= inner.len() {
                    let hours_str = &inner[hyph + 1..hyph + 3];
                    let hours = hours_str
                        .parse::<f64>()
                        .map_err(|_| serde::de::Error::custom("Failed to parse hours"))?;

                    // Parse timezone offset minutes (2 digits)
                    let mins = if hyph + 5 <= inner.len() {
                        let mins_str = &inner[hyph + 3..hyph + 5];
                        mins_str.parse::<f64>().unwrap_or(0.0)
                    } else {
                        0.0
                    };

                    // Apply timezone offset to convert to UTC
                    let offset_ms = (hours * 60.0 * 60.0 * 1000.0) + (mins * 60.0 * 1000.0);
                    if is_negative {
                        timestamp_ms -= offset_ms;
                    } else {
                        timestamp_ms += offset_ms;
                    }
                }

                // Create DateTime from adjusted timestamp
                match Utc.timestamp_millis_opt(timestamp_ms as i64) {
                    chrono::LocalResult::Single(dt) => Ok(dt.date_naive()),
                    _ => Err(serde::de::Error::custom("Invalid timestamp")),
                }
            } else {
                // No timezone offset - parse as timestamp and use date only (no time component)
                let timestamp_ms = inner
                    .parse::<i64>()
                    .map_err(|_| serde::de::Error::custom("Failed to parse timestamp"))?;

                match Utc.timestamp_millis_opt(timestamp_ms) {
                    chrono::LocalResult::Single(dt) => {
                        // Return date only (time set to 00:00:00)
                        let date = dt.date_naive();
                        Ok(date)
                    }
                    _ => Err(serde::de::Error::custom("Invalid timestamp")),
                }
            }
        } else {
            // Fallback to standard ISO format
            s.parse::<DateTime<Utc>>()
                .map(|s| s.date_naive())
                .map_err(serde::de::Error::custom)
        }
    }
}

mod dotnet_date_format_opt {
    use chrono::{DateTime, NaiveDate, TimeZone, Utc};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S>(date: &Option<NaiveDate>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match date {
            None => "/Date(-0)/".serialize(serializer),
            Some(date) => {
                let timestamp_ms = date
                    .and_hms_opt(0, 0, 0)
                    .unwrap()
                    .and_utc()
                    .timestamp_millis();
                let formatted = format!("/Date({})/", timestamp_ms);
                formatted.serialize(serializer)
            }
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<NaiveDate>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;

        // Handle special case: dates starting with /Date(- are considered null
        if s.starts_with("/Date(-") {
            return Ok(None);
        }

        // Handle .NET date format: "/Date(1316156400000-0700)/"
        if s.starts_with("/Date(") && s.ends_with(")/") {
            let inner = &s[6..s.len() - 2]; // Remove "/Date(" and ")/"

            // Find last - or + for timezone offset
            let (hyph_pos, is_negative) = if let Some(pos) = inner.rfind('-') {
                (Some(pos), true)
            } else if let Some(pos) = inner.rfind('+') {
                (Some(pos), false)
            } else {
                (None, true)
            };

            if let Some(hyph) = hyph_pos {
                // Parse timestamp before timezone offset
                let timestamp_str = &inner[..hyph];
                let mut timestamp_ms = timestamp_str
                    .parse::<f64>()
                    .map_err(|_| serde::de::Error::custom("Failed to parse timestamp"))?;

                // Parse timezone offset hours (2 digits)
                if hyph + 3 <= inner.len() {
                    let hours_str = &inner[hyph + 1..hyph + 3];
                    let hours = hours_str
                        .parse::<f64>()
                        .map_err(|_| serde::de::Error::custom("Failed to parse hours"))?;

                    // Parse timezone offset minutes (2 digits)
                    let mins = if hyph + 5 <= inner.len() {
                        let mins_str = &inner[hyph + 3..hyph + 5];
                        mins_str.parse::<f64>().unwrap_or(0.0)
                    } else {
                        0.0
                    };

                    // Apply timezone offset to convert to UTC
                    let offset_ms = (hours * 60.0 * 60.0 * 1000.0) + (mins * 60.0 * 1000.0);
                    if is_negative {
                        timestamp_ms -= offset_ms;
                    } else {
                        timestamp_ms += offset_ms;
                    }
                }

                // Create DateTime from adjusted timestamp
                match Utc.timestamp_millis_opt(timestamp_ms as i64) {
                    chrono::LocalResult::Single(dt) => Ok(Some(dt.date_naive())),
                    _ => Err(serde::de::Error::custom("Invalid timestamp")),
                }
            } else {
                // No timezone offset - parse as timestamp and use date only (no time component)
                let timestamp_ms = inner
                    .parse::<i64>()
                    .map_err(|_| serde::de::Error::custom("Failed to parse timestamp"))?;

                match Utc.timestamp_millis_opt(timestamp_ms) {
                    chrono::LocalResult::Single(dt) => {
                        // Return date only (time set to 00:00:00)
                        let date = dt.date_naive();
                        Ok(Some(date))
                    }
                    _ => Err(serde::de::Error::custom("Invalid timestamp")),
                }
            }
        } else {
            // Fallback to standard ISO format
            s.parse::<DateTime<Utc>>()
                .map(|s| Some(s.date_naive()))
                .map_err(serde::de::Error::custom)
        }
    }
}

/// Response wrapper for Bing Webmaster API JSON responses
///
/// All JSON responses from the Bing API are wrapped in a `{"d": data}` structure,
/// following the .NET WCF JSON serialization format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseWrapper<T> {
    /// The wrapped response data
    pub d: T,
}

/// Represents a URL that has been blocked from Bing's search index
///
/// Used to request temporary removal of content from Bing search results.
/// This can be for a single page or an entire directory.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockedUrl {
    /// The URL to be blocked (e.g., `https://example.com/page`)
    #[serde(rename = "Url")]
    pub url: String,

    /// The date when the block was requested
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Number of days until the block expires (if applicable)
    #[serde(rename = "DaysToExpire", skip_serializing_if = "Option::is_none")]
    pub days_to_expire: Option<i32>,

    /// Whether this blocks a single page or entire directory
    #[serde(rename = "EntityType")]
    pub entity_type: BlockedUrlEntityType,

    /// Type of removal requested (cache only or full removal)
    #[serde(rename = "RequestType")]
    pub request_type: BlockedUrlRequestType,
}

/// Specifies whether a block applies to a single page or directory
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum BlockedUrlEntityType {
    /// Block a single page
    Page = 0,
    /// Block an entire directory and all its contents
    Directory = 1,
}

/// Type of content removal requested
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum BlockedUrlRequestType {
    /// Remove from cache only, keep in search results
    CacheOnly = 0,
    /// Remove completely from search results and cache
    FullRemoval = 1,
}

/// Reasons for blocking page previews
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum BlockReason {
    /// Don't show preview
    NoPreview,
    /// Don't cache the page
    NoCache,
    /// Don't show snippet in search results
    NoSnippet,
    /// Don't index the page
    NoIndex,
    /// Don't show archived version
    NoArchive,
}

/// Geographic targeting settings for content
///
/// Allows you to specify which country or region specific content is targeted towards.
/// This helps Bing show the right content to users in different geographic locations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CountryRegionSettings {
    /// The date when this setting was configured
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Two-letter ISO country code (e.g., "US", "GB", "DE")
    #[serde(rename = "TwoLetterIsoCountryCode")]
    pub two_letter_iso_country_code: String,

    /// The scope of this geographic targeting setting
    #[serde(rename = "Type")]
    pub r#type: CountryRegionSettingsType,

    /// The URL or URL pattern this setting applies to
    #[serde(rename = "Url")]
    pub url: String,
}

/// Scope of geographic targeting
#[derive(Debug, Clone, Copy, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum CountryRegionSettingsType {
    /// Target a single page
    Page = 0,
    /// Target a directory and all its contents
    Directory = 1,
    /// Target the entire domain
    Domain = 2,
    /// Target a subdomain
    Subdomain = 3,
}

/// Crawl statistics for a website
///
/// Provides detailed metrics about how Bingbot crawls your website,
/// including HTTP response codes, errors, and index status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlStats {
    /// Count of pages returning other HTTP status codes not categorized below
    #[serde(rename = "AllOtherCodes")]
    pub all_other_codes: i64,

    /// Count of pages blocked by robots.txt
    #[serde(rename = "BlockedByRobotsTxt")]
    pub blocked_by_robots_txt: i64,

    /// Count of pages returning 2xx success codes
    #[serde(rename = "Code2xx")]
    pub code_2xx: i64,

    /// Count of pages returning 301 permanent redirect
    #[serde(rename = "Code301")]
    pub code_301: i64,

    /// Count of pages returning 302 temporary redirect
    #[serde(rename = "Code302")]
    pub code_302: i64,

    /// Count of pages returning 4xx client error codes
    #[serde(rename = "Code4xx")]
    pub code_4xx: i64,

    /// Count of pages returning 5xx server error codes
    #[serde(rename = "Code5xx")]
    pub code_5xx: i64,

    /// Count of connection timeouts
    #[serde(rename = "ConnectionTimeout")]
    pub connection_timeout: i64,

    /// Total number of pages crawled
    #[serde(rename = "CrawledPages")]
    pub crawled_pages: i64,

    /// Total number of crawl errors encountered
    #[serde(rename = "CrawlErrors")]
    pub crawl_errors: i64,

    /// Date of these statistics
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Count of DNS resolution failures
    #[serde(rename = "DnsFailures")]
    pub dns_failures: i64,

    /// Number of pages currently in Bing's index
    #[serde(rename = "InIndex")]
    pub in_index: i64,

    /// Number of inbound links to the site
    #[serde(rename = "InLinks")]
    pub in_links: i64,
}

/// Deep link information for search results
///
/// Deep links are additional links shown below a main search result,
/// helping users navigate directly to specific pages within your site.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeepLink {
    /// Position of this deep link in the search results
    #[serde(rename = "Position")]
    pub position: i32,

    /// Display title for the deep link
    #[serde(rename = "Title")]
    pub title: String,

    /// URL of the deep link
    #[serde(rename = "Url")]
    pub url: String,

    /// Weight/priority of this deep link
    #[serde(rename = "Weight")]
    pub weight: DeepLinkWeight,
}

/// Priority weight for deep links
///
/// Controls how prominently a deep link should be displayed in search results.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum DeepLinkWeight {
    /// Deep link is disabled
    Disabled = 0,
    /// Low priority
    Low = 1,
    /// Normal priority
    Normal = 2,
    /// High priority
    High = 3,
}

/// Algorithm-suggested deep link URL
///
/// URLs that Bing's algorithm suggests as good candidates for deep links.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeepLinkAlgoUrl {
    /// Number of deep links for this URL
    #[serde(rename = "DeepLinkCount")]
    pub deep_link_count: i32,

    /// Number of impressions this URL receives
    #[serde(rename = "Impressions")]
    pub impressions: i32,

    /// The suggested URL
    #[serde(rename = "Url")]
    pub url: String,
}

/// Blocked deep link
///
/// Represents a deep link that has been explicitly blocked from appearing in search results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeepLinkBlock {
    /// Source URL (the main search result)
    pub source_url: String,

    /// Target URL (the deep link being blocked)
    pub target_url: String,

    /// Type of block applied
    pub block_type: String,

    /// Reason for blocking this deep link
    pub reason: String,
}

/// Page preview block
///
/// Represents a page where preview features (snippet, cache, etc.) have been blocked.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PagePreviewBlock {
    /// URL of the page with blocked preview
    pub url: String,

    /// Reason for blocking the preview
    pub block_reason: BlockReason,

    /// Date when the block was applied
    pub blocked_date: NaiveDate,
}

/// Content submission API quota
///
/// Daily and monthly limits for the content submission API.
/// Content submission allows submitting page content directly to Bing (up to 10MB per request).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentSubmissionQuota {
    /// Daily submission quota remaining
    #[serde(rename = "DailyQuota")]
    pub daily_quota: i64,

    /// Monthly submission quota remaining
    #[serde(rename = "MonthlyQuota")]
    pub monthly_quota: i64,
}

/// Crawl rate settings for a site
///
/// Controls how frequently Bingbot crawls your site.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlSettings {
    /// Whether crawl boost feature is available for this site
    #[serde(rename = "CrawlBoostAvailable")]
    pub crawl_boost_available: bool,

    /// Whether crawl boost is currently enabled
    #[serde(rename = "CrawlBoostEnabled")]
    pub crawl_boost_enabled: bool,

    /// Crawl rate configuration data
    #[serde(rename = "CrawlRate")]
    pub crawl_rate: Vec<u8>,
}

/// Detailed query statistics for a specific date
///
/// More granular version of `QueryStats` with position data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetailedQueryStats {
    /// Number of clicks for this query
    #[serde(rename = "Clicks")]
    pub clicks: i64,

    /// Date of these statistics
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Number of impressions for this query
    #[serde(rename = "Impressions")]
    pub impressions: i64,

    /// Average position in search results
    #[serde(rename = "Position")]
    pub position: f64,
}

/// Search query performance statistics
///
/// Contains metrics about how a specific search query performs for your site,
/// including clicks, impressions, and ranking positions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryStats {
    /// Average position in search results when the page is clicked
    #[serde(rename = "AvgClickPosition")]
    pub avg_click_position: f64,

    /// Average position in search results when the page is shown (impression)
    #[serde(rename = "AvgImpressionPosition")]
    pub avg_impression_position: f64,

    /// Number of times users clicked through to your site from search results
    #[serde(rename = "Clicks")]
    pub clicks: i64,

    /// Date of these statistics
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Number of times your site appeared in search results (impressions)
    #[serde(rename = "Impressions")]
    pub impressions: i64,

    /// The search query string
    #[serde(rename = "Query")]
    pub query: String,
}

/// Crawl issues encountered for a URL
///
/// This is a flags enumeration that supports bitwise combination of values.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.UrlWithCrawlIssues.CrawlIssues
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum CrawlIssues {
    /// No issues
    None = 0,
    /// HTTP 301 permanent redirect
    Code301 = 1,
    /// HTTP 302 temporary redirect
    Code302 = 2,
    /// HTTP 4xx client error
    Code4xx = 4,
    /// HTTP 5xx server error
    Code5xx = 8,
    /// URL blocked by robots.txt
    BlockedByRobotsTxt = 16,
    /// Page contains malware
    ContainsMalware = 32,
    /// Important URL blocked by robots.txt
    ImportantUrlBlockedByRobotsTxt = 64,
    /// DNS resolution errors
    DnsErrors = 128,
    /// Request timeout errors
    TimeOutErrors = 256,
}

/// URL with crawl issues
///
/// Represents a URL that Bingbot encountered problems crawling,
/// along with information about the type of issues.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.UrlWithCrawlIssues
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UrlWithCrawlIssues {
    /// HTTP status code returned when crawling this URL
    #[serde(rename = "HttpCode")]
    pub http_code: i32,

    /// Crawl issues encountered (flags enum, can be combined)
    #[serde(rename = "Issues")]
    pub issues: CrawlIssues,

    /// The URL that has crawl issues
    #[serde(rename = "Url")]
    pub url: String,

    /// Number of inbound links pointing to this URL
    #[serde(rename = "InLinks")]
    pub in_links: i64,
}

/// RSS or Atom feed information
///
/// Contains details about a submitted feed, including its status and crawl information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Feed {
    /// Whether the feed is compressed (gzipped)
    #[serde(rename = "Compressed")]
    pub compressed: bool,

    /// Size of the feed file in bytes
    #[serde(rename = "FileSize")]
    pub file_size: i64,

    /// When the feed was last crawled by Bing
    #[serde(rename = "LastCrawled", with = "dotnet_date_format_opt")]
    pub last_crawled: Option<NaiveDate>,

    /// Current status of the feed (e.g., "Active", "Pending")
    #[serde(rename = "Status")]
    pub status: String,

    /// When the feed was submitted
    #[serde(rename = "Submitted", with = "dotnet_date_format_opt")]
    pub submitted: Option<NaiveDate>,

    /// Feed type (e.g., "RSS", "Atom")
    #[serde(rename = "Type")]
    pub r#type: String,

    /// URL of the feed
    #[serde(rename = "Url")]
    pub url: String,

    /// Number of URLs contained in the feed
    #[serde(rename = "UrlCount")]
    pub url_count: i32,
}

/// Website information and verification status
///
/// Contains verification codes and status for a site in Bing Webmaster Tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Site {
    /// Authentication code for meta tag verification
    #[serde(rename = "AuthenticationCode")]
    pub authentication_code: String,

    /// DNS TXT record code for DNS verification
    #[serde(rename = "DnsVerificationCode")]
    pub dns_verification_code: String,

    /// Whether the site ownership has been verified
    #[serde(rename = "IsVerified")]
    pub is_verified: bool,

    /// The site URL (e.g., `https://example.com`)
    #[serde(rename = "Url")]
    pub url: String,
}

/// User roles and permissions for a site
///
/// Represents a user's access permissions for a specific site in Bing Webmaster Tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SiteRoles {
    /// Date when this role was assigned
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Delegation code for transferring site ownership
    #[serde(rename = "DelegatedCode")]
    pub delegated_code: Option<String>,

    /// Email of the user who owns the delegation code
    #[serde(rename = "DelegatedCodeOwnerEmail")]
    pub delegated_code_owner_email: Option<String>,

    /// Email of the user who delegated access
    #[serde(rename = "DelegatorEmail")]
    pub delegator_email: Option<String>,

    /// Email of the user with this role
    #[serde(rename = "Email")]
    pub email: String,

    /// Whether this role assignment has expired
    #[serde(rename = "Expired")]
    pub expired: bool,

    /// The role assigned to the user
    #[serde(rename = "Role")]
    pub role: UserRole,

    /// The site URL this role applies to
    #[serde(rename = "Site")]
    pub site: String,

    /// The verification site URL
    #[serde(rename = "VerificationSite")]
    pub verification_site: String,
}

/// User role permissions for site access
///
/// Defines the level of access a user has to a site in Bing Webmaster Tools.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.SiteRoles.UserRole
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum UserRole {
    /// User has full administrative permissions
    Administrator = 0,
    /// User has read-only permissions
    ReadOnly = 1,
    /// User has read and write permissions
    ReadWrite = 2,
}

/// Detailed information about a specific URL
///
/// Contains comprehensive metadata about a URL including crawl status,
/// size, and link information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UrlInfo {
    /// Number of anchor links pointing to this URL
    #[serde(rename = "AnchorCount")]
    pub anchor_count: i32,

    /// When Bing first discovered this URL
    #[serde(rename = "DiscoveryDate", with = "dotnet_date_format")]
    pub discovery_date: NaiveDate,

    /// Size of the document in bytes
    #[serde(rename = "DocumentSize")]
    pub document_size: i64,

    /// HTTP status code returned when crawling
    #[serde(rename = "HttpStatus")]
    pub http_status: i32,

    /// Whether this is a page (true) or directory (false)
    #[serde(rename = "IsPage")]
    pub is_page: bool,

    /// When Bing last crawled this URL
    #[serde(rename = "LastCrawledDate", with = "dotnet_date_format")]
    pub last_crawled_date: NaiveDate,

    /// Total number of child URLs under this URL
    #[serde(rename = "TotalChildUrlCount")]
    pub total_child_url_count: i32,

    /// The URL
    #[serde(rename = "Url")]
    pub url: String,
}

/// Traffic statistics for a specific URL
///
/// Contains click and impression data for a URL in search results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UrlTrafficInfo {
    /// Number of clicks this URL received
    #[serde(rename = "Clicks")]
    pub clicks: i32,

    /// Number of times this URL appeared in search results
    #[serde(rename = "Impressions")]
    pub impressions: i32,

    /// Whether this is a page (true) or directory (false)
    #[serde(rename = "IsPage")]
    pub is_page: bool,

    /// The URL
    #[serde(rename = "Url")]
    pub url: String,
}

/// URL submission API quota
///
/// Daily and monthly limits for the URL submission API.
/// Allows submitting up to 10,000 URLs per day for crawling.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UrlSubmissionQuota {
    /// Daily URL submission quota remaining
    #[serde(rename = "DailyQuota")]
    pub daily_quota: i32,

    /// Monthly URL submission quota remaining
    #[serde(rename = "MonthlyQuota")]
    pub monthly_quota: i32,
}

/// Inbound link counts for URLs
///
/// Contains a list of URLs and how many inbound links each has.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkCounts {
    /// List of URLs with their link counts
    #[serde(rename = "Links")]
    pub links: Vec<LinkCount>,

    /// Total number of pages in the result set
    #[serde(rename = "TotalPages")]
    pub total_pages: i32,
}

/// Link count for a specific URL
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkCount {
    /// Number of inbound links to this URL
    #[serde(rename = "Count")]
    pub count: i32,

    /// The URL
    #[serde(rename = "Url")]
    pub url: String,
}

/// Detailed inbound link information
///
/// Contains specific details about inbound links including anchor text.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkDetails {
    /// List of detailed link information
    #[serde(rename = "Details")]
    pub details: Vec<LinkDetail>,

    /// Total number of pages in the result set
    #[serde(rename = "TotalPages")]
    pub total_pages: i32,
}

/// Detail about a specific inbound link
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkDetail {
    /// The anchor text used for the link
    #[serde(rename = "AnchorText")]
    pub anchor_text: String,

    /// The source URL of the link
    #[serde(rename = "Url")]
    pub url: String,
}

/// Query parameter configuration
///
/// Represents a URL query parameter that should be ignored or included during crawling.
/// This helps prevent duplicate content issues from URL parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryParameter {
    /// Date when this parameter configuration was set
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Whether this parameter is enabled (should be ignored)
    #[serde(rename = "IsEnabled")]
    pub is_enabled: bool,

    /// The query parameter name (e.g., "sessionid", "ref")
    #[serde(rename = "Parameter")]
    pub parameter: String,

    /// Source of this parameter configuration
    #[serde(rename = "Source")]
    pub source: i32,
}

/// Combined ranking and traffic statistics
///
/// Aggregated metrics for site performance in search results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RankAndTrafficStats {
    /// Total number of clicks
    #[serde(rename = "Clicks")]
    pub clicks: i64,

    /// Date of these statistics
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Total number of impressions
    #[serde(rename = "Impressions")]
    pub impressions: i64,
}

/// Crawl date filter options
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.CrawlDateFilter
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum CrawlDateFilter {
    /// Any crawl date
    Any = 0,
    /// Last week
    LastWeek = 1,
    /// Last two weeks
    LastTwoWeeks = 2,
}

/// Discovered date filter options
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.DiscoveredDateFilter
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum DiscoveredDateFilter {
    /// Any discovered date
    Any = 0,
    /// Last week
    LastWeek = 1,
    /// Last month
    LastMonth = 2,
}

/// Document flags filters
///
/// Flags enumeration for filtering by document properties.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.DocFlagsFilters
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum DocFlagsFilters {
    /// Any document flags
    Any = 0,
    /// Document is blocked by robots.txt
    IsBlockedByRobotsTxt = 1,
}

/// HTTP code filters
///
/// Flags enumeration for filtering by HTTP status codes.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.HttpCodeFilters
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum HttpCodeFilters {
    /// Any HTTP code
    Any = 0,
    /// 2xx success codes
    Code2xx = 1,
    /// 3xx redirect codes
    Code3xx = 2,
    /// 301 permanent redirect
    Code301 = 4,
    /// 302 temporary redirect
    Code302 = 8,
    /// 4xx client error codes
    Code4xx = 16,
    /// 5xx server error codes
    Code5xx = 32,
    /// All other codes
    AllOthers = 64,
}

/// Filter properties for queries
///
/// Used to filter URL information queries by various criteria.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.FilterProperties
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterProperties {
    /// Filter by crawl date range
    #[serde(rename = "CrawlDateFilter")]
    pub crawl_date_filter: CrawlDateFilter,

    /// Filter by discovered date range
    #[serde(rename = "DiscoveredDateFilter")]
    pub discovered_date_filter: DiscoveredDateFilter,

    /// Filter by document flags
    #[serde(rename = "DocFlagsFilters")]
    pub doc_flags_filters: DocFlagsFilters,

    /// Filter by HTTP status codes
    #[serde(rename = "HttpCodeFilters")]
    pub http_code_filters: HttpCodeFilters,
}

/// URL fetched on demand
///
/// Result of requesting Bing to fetch a specific URL.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.FetchedUrl
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FetchedUrl {
    /// The URL that was fetched
    #[serde(rename = "Url")]
    pub url: String,

    /// When the URL was fetched
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Whether the fetch request has expired
    #[serde(rename = "Expired")]
    pub expired: bool,

    /// Whether the URL was successfully fetched
    #[serde(rename = "Fetched")]
    pub fetched: bool,
}

/// Detailed information about a fetched URL
///
/// Extended version of `FetchedUrl` with document content and HTTP headers.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.FetchedUrlDetails
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FetchedUrlDetails {
    /// The URL that was fetched
    #[serde(rename = "Url")]
    pub url: String,

    /// When the URL was fetched
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// The document content returned
    #[serde(rename = "Document")]
    pub document: String,

    /// HTTP response headers
    #[serde(rename = "Headers")]
    pub headers: String,

    /// HTTP status message
    #[serde(rename = "Status")]
    pub status: String,
}

/// Keyword search statistics
///
/// Performance metrics for a specific search keyword.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.Keyword
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Keyword {
    /// The search query/keyword
    #[serde(rename = "Query")]
    pub query: String,

    /// Number of exact match impressions for this keyword
    #[serde(rename = "Impressions")]
    pub impressions: i64,

    /// Number of broad match impressions for this keyword
    #[serde(rename = "BroadImpressions")]
    pub broad_impressions: i64,
}

/// Keyword statistics for a specific date
///
/// Performance metrics for a keyword on a particular date.
///
/// Reference: Microsoft.Bing.Webmaster.Api.Interfaces.KeywordStats
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeywordStats {
    /// The search query/keyword
    #[serde(rename = "Query")]
    pub query: String,

    /// Number of exact match impressions
    #[serde(rename = "Impressions")]
    pub impressions: i64,

    /// Number of broad match impressions
    #[serde(rename = "BroadImpressions")]
    pub broad_impressions: i64,

    /// Date of these statistics
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,
}

/// Site migration information
///
/// Represents a site move/migration from one URL to another.
/// Used to inform Bing about domain changes or HTTPS migrations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SiteMove {
    /// Original site URL (source)
    #[serde(rename = "SourceSite")]
    pub source_site: String,

    /// New site URL (target/destination)
    #[serde(rename = "TargetSite")]
    pub target_site: String,

    /// Date when the site move was registered
    #[serde(rename = "Date", with = "dotnet_date_format")]
    pub date: NaiveDate,

    /// Current status of the site move (e.g., "InProgress", "Complete")
    #[serde(rename = "Status")]
    pub status: String,
}

/// Site move configuration settings
///
/// Settings required to configure a site migration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SiteMoveSettings {
    /// Target site URL (new location)
    #[serde(rename = "TargetSite")]
    pub target_site: String,

    /// Validation tag to verify ownership of target site
    #[serde(rename = "ValidationTag")]
    pub validation_tag: String,
}