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
//! Contains all other input validation functions.
//!
//! These functions are generally not related to a specific Discord model.

use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
    time::{SystemTime, UNIX_EPOCH},
};
use twilight_model::datetime::Timestamp;

/// Maximum amount of days for messages to be deleted upon ban.
pub const CREATE_GUILD_BAN_DELETE_MESSAGE_DAYS_MAX: u64 = 7;

/// Maximum amount of time a member can be timed out for.
pub const COMMUNICATION_DISABLED_MAX_DURATION: i64 = 28 * 24 * 60 * 60;

/// Maximum amount of messages to get.
pub const GET_CHANNEL_MESSAGES_LIMIT_MAX: u64 = 100;

/// Minimum amount of messages to get.
pub const GET_CHANNEL_MESSAGES_LIMIT_MIN: u64 = 1;

/// Maximum amount of guilds to get.
pub const GET_CURRENT_USER_GUILDS_LIMIT_MAX: u64 = 200;

/// Minimum amount of guilds to get.
pub const GET_CURRENT_USER_GUILDS_LIMIT_MIN: u64 = 1;

/// Maximum amount of audit log entries to list.
pub const GET_GUILD_AUDIT_LOG_LIMIT_MAX: u64 = 100;

/// Minimum amount of audit log entries to list.
pub const GET_GUILD_AUDIT_LOG_LIMIT_MIN: u64 = 1;

/// Maximum amount of guild members to list.
pub const GET_GUILD_MEMBERS_LIMIT_MAX: u64 = 1000;

/// Minimum amount of guild members to list.
pub const GET_GUILD_MEMBERS_LIMIT_MIN: u64 = 1;

/// Maximum amount of users to return when getting reactions.
pub const GET_REACTIONS_LIMIT_MIN: u64 = 1;

/// Minimum amount of users to return when getting reactions.
pub const GET_REACTIONS_LIMIT_MAX: u64 = 100;

/// Maximum length of a guild's name.
pub const GUILD_NAME_LENGTH_MAX: usize = 100;

/// Minimum length of a guild's name.
pub const GUILD_NAME_LENGTH_MIN: usize = 2;

/// Maximum amount of days to prune users from a guild.
pub const GUILD_PRUNE_DAYS_MAX: u64 = 30;

/// Minimum amount of days to prune users from a guild.
pub const GUILD_PRUNE_DAYS_MIN: u64 = 1;

/// Maximum length of an invite's age, in seconds.
pub const INVITE_AGE_MAX: u64 = 604_800;

/// Maximum uses of an invite, if not unlimited.
pub const INVITE_USES_MAX: u64 = 100;

/// Maximum length of a maximum.
pub const NICKNAME_LIMIT_MAX: usize = 32;

/// Minimum length of a nickname.
pub const NICKNAME_LIMIT_MIN: usize = 1;

/// Maximum length of a scheduled event's description.
pub const SCHEDULED_EVENT_DESCRIPTION_MAX: usize = 1000;

/// Minimum length of a scheduled event's description.
pub const SCHEDULED_EVENT_DESCRIPTION_MIN: usize = 1;

/// Maximum amount of scheduled event users to get.
pub const SCHEDULED_EVENT_GET_USERS_MAX: u64 = 100;

/// Minimum amount of scheduled event users to get.
pub const SCHEDULED_EVENT_GET_USERS_MIN: u64 = 1;

/// Maximum length of a scheduled event's name.
pub const SCHEDULED_EVENT_NAME_MAX: usize = 100;

/// Minimum length of a scheduled event's name.
pub const SCHEDULED_EVENT_NAME_MIN: usize = 1;

/// Maximum amount of guild members to search for.
pub const SEARCH_GUILD_MEMBERS_LIMIT_MAX: u64 = 1000;

/// Minimum amount of guild members to search for.
pub const SEARCH_GUILD_MEMBERS_LIMIT_MIN: u64 = 1;

/// Maximum stage instance topic length.
pub const STAGE_TOPIC_LENGTH_MAX: usize = 120;

/// Minimum stage instance topic length.
pub const STAGE_TOPIC_LENGTH_MIN: usize = 1;

/// Maximum length of a guild template description.
pub const TEMPLATE_DESCRIPTION_LENGTH_MAX: usize = 120;

/// Maximum length of a guild template name.
pub const TEMPLATE_NAME_LENGTH_MAX: usize = 100;

/// Minimum length of a guild template name.
pub const TEMPLATE_NAME_LENGTH_MIN: usize = 1;

/// Maximum length of a username.
pub const USERNAME_LIMIT_MAX: usize = 32;

/// Minimum length of a username.
pub const USERNAME_LIMIT_MIN: usize = 2;

/// A field is not valid.
#[derive(Debug)]
pub struct ValidationError {
    /// Type of error that occurred.
    kind: ValidationErrorType,
}

impl ValidationError {
    /// Immutable reference to the type of error that occurred.
    #[must_use = "retrieving the type has no effect if left unused"]
    pub const fn kind(&self) -> &ValidationErrorType {
        &self.kind
    }

    /// Consume the error, returning the source error if there is any.
    #[allow(clippy::unused_self)]
    #[must_use = "consuming the error and retrieving the source has no effect if left unused"]
    pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
        None
    }

    /// Consume the error, returning the owned error type and the source error.
    #[must_use = "consuming the error into its parts has no effect if left unused"]
    pub fn into_parts(self) -> (ValidationErrorType, Option<Box<dyn Error + Send + Sync>>) {
        (self.kind, None)
    }
}

impl Display for ValidationError {
    #[allow(clippy::too_many_lines)]
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match &self.kind {
            ValidationErrorType::CreateGuildBanDeleteMessageDays {
                days: delete_message_days,
            } => {
                f.write_str("provided create guild ban delete_message_days is ")?;
                Display::fmt(delete_message_days, f)?;
                f.write_str(", but it must be at most ")?;

                Display::fmt(&CREATE_GUILD_BAN_DELETE_MESSAGE_DAYS_MAX, f)
            }
            ValidationErrorType::CommunicationDisabledUntil { .. } => {
                f.write_str("provided timestamp is too far in the future")
            }
            ValidationErrorType::GetChannelMessages { limit } => {
                f.write_str("provided get guild members limit is ")?;
                Display::fmt(limit, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&GET_CHANNEL_MESSAGES_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&GET_CHANNEL_MESSAGES_LIMIT_MAX, f)
            }
            ValidationErrorType::GetCurrentUserGuilds { limit } => {
                f.write_str("provided get current user guilds limit is ")?;
                Display::fmt(limit, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&GET_CURRENT_USER_GUILDS_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&GET_CURRENT_USER_GUILDS_LIMIT_MAX, f)
            }
            ValidationErrorType::GetGuildAuditLog { limit } => {
                f.write_str("provided get guild audit log limit is ")?;
                Display::fmt(limit, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MAX, f)
            }
            ValidationErrorType::GetGuildMembers { limit } => {
                f.write_str("provided get guild members limit is ")?;
                Display::fmt(limit, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MAX, f)
            }
            ValidationErrorType::GetReactions { limit } => {
                f.write_str("provided get reactions limit is ")?;
                Display::fmt(limit, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&GET_REACTIONS_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&GET_REACTIONS_LIMIT_MAX, f)
            }
            ValidationErrorType::GuildName { len } => {
                f.write_str("provided guild name length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&GUILD_NAME_LENGTH_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&GUILD_NAME_LENGTH_MAX, f)
            }
            ValidationErrorType::GuildPruneDays { days } => {
                f.write_str("provided prune days is ")?;
                Display::fmt(days, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&GUILD_PRUNE_DAYS_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&GUILD_PRUNE_DAYS_MAX, f)
            }
            ValidationErrorType::InviteMaxAge { max_age } => {
                f.write_str("provided invite max_age is ")?;
                Display::fmt(max_age, f)?;
                f.write_str(", but it must be at most ")?;

                Display::fmt(&INVITE_AGE_MAX, f)
            }
            ValidationErrorType::InviteMaxUses { max_uses } => {
                f.write_str("provided invite max_uses is ")?;
                Display::fmt(max_uses, f)?;
                f.write_str(", but it must be at most ")?;

                Display::fmt(&INVITE_USES_MAX, f)
            }
            ValidationErrorType::Nickname { len } => {
                f.write_str("provided nickname length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&NICKNAME_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&NICKNAME_LIMIT_MAX, f)
            }
            ValidationErrorType::ScheduledEventDescription { len } => {
                f.write_str("provided scheduled event description is length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&SCHEDULED_EVENT_DESCRIPTION_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&SCHEDULED_EVENT_DESCRIPTION_MAX, f)
            }
            ValidationErrorType::ScheduledEventGetUsers { limit } => {
                f.write_str("provided scheduled event get users limit is ")?;
                Display::fmt(limit, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&SCHEDULED_EVENT_GET_USERS_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&SCHEDULED_EVENT_GET_USERS_MAX, f)
            }
            ValidationErrorType::ScheduledEventName { len } => {
                f.write_str("provided scheduled event name is length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&SCHEDULED_EVENT_NAME_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&SCHEDULED_EVENT_NAME_MAX, f)
            }
            ValidationErrorType::SearchGuildMembers { limit } => {
                f.write_str("provided search guild members limit is ")?;
                Display::fmt(limit, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&SEARCH_GUILD_MEMBERS_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&SEARCH_GUILD_MEMBERS_LIMIT_MAX, f)
            }
            ValidationErrorType::StageTopic { len } => {
                f.write_str("provided stage instance topic length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&STAGE_TOPIC_LENGTH_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&STAGE_TOPIC_LENGTH_MAX, f)
            }
            ValidationErrorType::TemplateDescription { len } => {
                f.write_str("provided guild template description topic length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at most ")?;

                Display::fmt(&TEMPLATE_DESCRIPTION_LENGTH_MAX, f)
            }
            ValidationErrorType::TemplateName { len } => {
                f.write_str("provided guild template name length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&TEMPLATE_NAME_LENGTH_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&TEMPLATE_NAME_LENGTH_MAX, f)
            }
            ValidationErrorType::Username { len } => {
                f.write_str("provided username length is ")?;
                Display::fmt(len, f)?;
                f.write_str(", but it must be at least ")?;
                Display::fmt(&USERNAME_LIMIT_MIN, f)?;
                f.write_str(" and at most ")?;

                Display::fmt(&USERNAME_LIMIT_MAX, f)
            }
        }
    }
}

impl Error for ValidationError {}

/// Type of [`ValidationError`] that occurred.
#[derive(Debug)]
pub enum ValidationErrorType {
    /// Provided create guild ban delete message days was invalid.
    CreateGuildBanDeleteMessageDays {
        /// Invalid days.
        days: u64,
    },
    /// Provided timestamp is too far in the future.
    CommunicationDisabledUntil {
        /// Invalid timestamp.
        timestamp: Timestamp,
    },
    /// Provided get channel messages limit was invalid.
    GetChannelMessages {
        /// Invalid limit.
        limit: u64,
    },
    /// Provided get current user guilds limit was invalid.
    GetCurrentUserGuilds {
        /// Invalid limit.
        limit: u64,
    },
    /// Provided get guild audit log limit was invalid.
    GetGuildAuditLog {
        /// Invalid limit.
        limit: u64,
    },
    /// Provided get guild members limit was invalid.
    GetGuildMembers {
        /// Invalid limit.
        limit: u64,
    },
    /// Provided get reactions limit was invalid.
    GetReactions {
        /// Invalid limit.
        limit: u64,
    },
    /// Provided guild name was invalid.
    GuildName {
        /// Invalid length.
        len: usize,
    },
    /// Provided guild prune days was invalid.
    GuildPruneDays {
        /// Invalid days.
        days: u64,
    },
    /// Provided invite max age was invalid.
    InviteMaxAge {
        /// Invalid age.
        max_age: u64,
    },
    /// Provided invite max uses was invalid.
    InviteMaxUses {
        /// Invalid age.
        max_uses: u64,
    },
    /// Provided nickname length was invalid.
    Nickname {
        /// Invalid length.
        len: usize,
    },
    /// Scheduled event description is invalid.
    ScheduledEventDescription {
        /// Invalid length.
        len: usize,
    },
    /// Scheduled event get users limit is invalid.
    ScheduledEventGetUsers {
        /// Invalid limit.
        limit: u64,
    },
    /// Scheduled event name is invalid.
    ScheduledEventName {
        /// Invalid length.
        len: usize,
    },
    /// Provided search guild members limit was invalid.
    SearchGuildMembers {
        /// Invalid limit.
        limit: u64,
    },
    /// Provided stage instance topic was invalid.
    StageTopic {
        /// Invalid length.
        len: usize,
    },
    /// Provided guild template description was invalid.
    TemplateDescription {
        /// Invalid length.
        len: usize,
    },
    /// Provided guild template name was invalid.
    TemplateName {
        /// Invalid length.
        len: usize,
    },
    /// Provided username length was invalid.
    Username {
        /// Invalid length.
        len: usize,
    },
}

/// Ensure that the delete message days amount for the Create Guild Ban request
/// is correct.
///
/// The days must be at most [`CREATE_GUILD_BAN_DELETE_MESSAGE_DAYS_MAX`]. This
/// is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`CreateGuildBanDeleteMessageDays`] if the days is
/// invalid.
///
/// [`CreateGuildBanDeleteMessageDays`]: ValidationErrorType::CreateGuildBanDeleteMessageDays
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#create-guild-ban
pub const fn create_guild_ban_delete_message_days(days: u64) -> Result<(), ValidationError> {
    if days <= CREATE_GUILD_BAN_DELETE_MESSAGE_DAYS_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::CreateGuildBanDeleteMessageDays { days },
        })
    }
}

/// Validate that a timeout time is not too far in the future.
///
/// The time must not be farther than 28 days in the future.
///
/// # Errors
///
///
#[allow(clippy::cast_possible_wrap)] // casting of unix timestamp should never wrap
pub fn communication_disabled_until(timestamp: Timestamp) -> Result<(), ValidationError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| ValidationError {
            kind: ValidationErrorType::CommunicationDisabledUntil { timestamp },
        })?;

    let end = timestamp.as_secs();

    if end - now.as_secs() as i64 <= COMMUNICATION_DISABLED_MAX_DURATION {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::CommunicationDisabledUntil { timestamp },
        })
    }
}

/// Ensure that the limit for the Get Channel Messages request is correct.
///
/// The limit must be at least [`GET_CHANNEL_MESSAGES_LIMIT_MIN`] and at most
/// [`GET_CHANNEL_MESSAGES_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetChannelMessages`] if the limit is invalid.
///
/// [`GetChannelMessages`]: ValidationErrorType::GetChannelMessages
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#get-channel-messages
pub const fn get_channel_messages_limit(limit: u64) -> Result<(), ValidationError> {
    if limit >= GET_CHANNEL_MESSAGES_LIMIT_MIN && limit <= GET_CHANNEL_MESSAGES_LIMIT_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::GetChannelMessages { limit },
        })
    }
}

/// Ensure that the limit for the Get Current User Guilds request is correct.
///
/// The limit must be at least [`GET_CURRENT_USER_GUILDS_LIMIT_MIN`] and at most
/// [`GET_CURRENT_USER_GUILDS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetCurrentUserGuilds`] if the limit is invalid.
///
/// [`GetCurrentUserGuilds`]: ValidationErrorType::GetCurrentUserGuilds
/// [this documentation entry]: https://discord.com/developers/docs/resources/user#get-current-user-guilds
pub const fn get_current_user_guilds_limit(limit: u64) -> Result<(), ValidationError> {
    if limit >= GET_CURRENT_USER_GUILDS_LIMIT_MIN && limit <= GET_CURRENT_USER_GUILDS_LIMIT_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::GetCurrentUserGuilds { limit },
        })
    }
}

/// Ensure that the limit for the Get Guild Audit Log endpoint is correct.
///
/// The limit must be at least [`GET_GUILD_AUDIT_LOG_LIMIT_MIN`] and at most
/// [`GET_GUILD_AUDIT_LOG_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetGuildAuditLog`] if the limit is invalid.
///
/// [`GetGuildAuditLog`]: ValidationErrorType::GetGuildAuditLog
/// [this documentation entry]: https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log
pub const fn get_guild_audit_log_limit(limit: u64) -> Result<(), ValidationError> {
    if limit >= GET_GUILD_AUDIT_LOG_LIMIT_MIN && limit <= GET_GUILD_AUDIT_LOG_LIMIT_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::GetGuildAuditLog { limit },
        })
    }
}

/// Ensure that the limit for the Get Guild Members endpoint is correct.
///
/// The limit must be at least [`GET_GUILD_MEMBERS_LIMIT_MIN`] and at most
/// [`GET_GUILD_MEMBERS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetGuildMembers`] if the limit is invalid.
///
/// [`GetGuildMembers`]: ValidationErrorType::GetGuildMembers
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#list-guild-members
pub const fn get_guild_members_limit(limit: u64) -> Result<(), ValidationError> {
    if limit >= GET_GUILD_MEMBERS_LIMIT_MIN && limit <= GET_GUILD_MEMBERS_LIMIT_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::GetGuildMembers { limit },
        })
    }
}

/// Ensure that the limit for the Get Reactions endpoint is correct.
///
/// The limit must be at least [`GET_REACTIONS_LIMIT_MIN`] and at most
/// [`GET_REACTIONS_LIMIT_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetReactions`] if the limit is invalid.
///
/// [`GetReactions`]: ValidationErrorType::GetReactions
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#get-reactions
pub const fn get_reactions_limit(limit: u64) -> Result<(), ValidationError> {
    if limit >= GET_REACTIONS_LIMIT_MIN && limit <= GET_REACTIONS_LIMIT_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::GetReactions { limit },
        })
    }
}

/// Ensure that a guild name's length is correct.
///
/// The length must be at least [`GUILD_NAME_LENGTH_MIN`] and at most
/// [`GUILD_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GuildName`] if the length is invalid.
///
/// [`GuildName`]: ValidationErrorType::GuildName
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#guild-object
pub fn guild_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = name.as_ref().chars().count();

    if (GUILD_NAME_LENGTH_MIN..=GUILD_NAME_LENGTH_MAX).contains(&len) {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::GuildName { len },
        })
    }
}

/// Ensure that the days to prune members from a guild is correct.
///
/// The days must be at least [`GUILD_PRUNE_DAYS_MIN`] and at most
/// [`GUILD_PRUNE_DAYS_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GuildPruneDays`] if the days is invalid.
///
/// [`GuildPruneDays`]: ValidationErrorType::GuildPruneDays
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#get-guild-prune-count
pub const fn guild_prune_days(days: u64) -> Result<(), ValidationError> {
    if days >= GUILD_PRUNE_DAYS_MIN && days <= GUILD_PRUNE_DAYS_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::GuildPruneDays { days },
        })
    }
}

/// Ensure that the invite max age is correct.
///
/// The age must be at most [`INVITE_AGE_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`InviteMaxAge`] if the age is invalid.
///
/// [`InviteMaxAge`]: ValidationErrorType::InviteMaxAge
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#create-channel-invite
pub const fn invite_max_age(max_age: u64) -> Result<(), ValidationError> {
    if max_age <= INVITE_AGE_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::InviteMaxAge { max_age },
        })
    }
}

/// Ensure that the invite max uses is correct.
///
/// The age must be at most [`INVITE_USES_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`InviteMaxUses`] if the uses is invalid.
///
/// [`InviteMaxUses`]: ValidationErrorType::InviteMaxUses
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#create-channel-invite
pub const fn invite_max_uses(max_uses: u64) -> Result<(), ValidationError> {
    if max_uses <= INVITE_USES_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::InviteMaxUses { max_uses },
        })
    }
}

/// Ensure that the nickname length is correct.
///
/// The length must be at least [`NICKNAME_LIMIT_MIN`] and at most
/// [`NICKNAME_LIMIT_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`Nickname`] if the length is invalid.
///
/// [`Nickname`]: ValidationErrorType::Nickname
/// [this documentation entry]: https://discord.com/developers/docs/resources/user#usernames-and-nicknames
pub fn nickname(nickname: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = nickname.as_ref().chars().count();

    if (NICKNAME_LIMIT_MIN..=NICKNAME_LIMIT_MAX).contains(&len) {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::Nickname { len },
        })
    }
}

/// Ensure that a scheduled event's description is correct.
///
/// The length must be at least [`SCHEDULED_EVENT_DESCRIPTION_MIN`] and at most
/// [`SCHEDULED_EVENT_DESCRIPTION_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`ScheduledEventDescription`] if the length is
/// invalid.
///
/// [`ScheduledEventDescription`]: ValidationErrorType::ScheduledEventDescription
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-structure
pub fn scheduled_event_description(description: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = description.as_ref().chars().count();

    if (SCHEDULED_EVENT_DESCRIPTION_MIN..=SCHEDULED_EVENT_DESCRIPTION_MAX).contains(&len) {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::ScheduledEventDescription { len },
        })
    }
}

/// Ensure that a scheduled event's get users limit amount is correct.
///
/// The length must be at least [`SCHEDULED_EVENT_GET_USERS_MIN`] and at most
/// [`SCHEDULED_EVENT_GET_USERS_MAX`]. This is based on [this documentation
/// entry].
///
/// # Errors
///
/// Returns an error of type [`ScheduledEventGetUsers`] if the limit is invalid.
///
/// [`ScheduledEventGetUsers`]: ValidationErrorType::ScheduledEventGetUsers
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event-users-query-string-params
pub const fn scheduled_event_get_users(limit: u64) -> Result<(), ValidationError> {
    if limit <= SCHEDULED_EVENT_GET_USERS_MIN && limit >= SCHEDULED_EVENT_GET_USERS_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::ScheduledEventGetUsers { limit },
        })
    }
}

/// Ensure that a scheduled event's name is correct.
///
/// The length must be at least [`SCHEDULED_EVENT_NAME_MIN`] and at most
/// [`SCHEDULED_EVENT_NAME_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`ScheduledEventName`] if the length is invalid.
///
/// [`ScheduledEventName`]: ValidationErrorType::ScheduledEventName
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-structure
pub fn scheduled_event_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = name.as_ref().chars().count();

    if (SCHEDULED_EVENT_NAME_MIN..=SCHEDULED_EVENT_NAME_MAX).contains(&len) {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::ScheduledEventName { len },
        })
    }
}

/// Ensure that the limit for the Search Guild Members endpoint is correct.
///
/// The limit must be at least [`SEARCH_GUILD_MEMBERS_LIMIT_MIN`] and at most
/// [`SEARCH_GUILD_MEMBERS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`SearchGuildMembers`] if the limit is invalid.
///
/// [`SearchGuildMembers`]: ValidationErrorType::SearchGuildMembers
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#search-guild-members
pub const fn search_guild_members_limit(limit: u64) -> Result<(), ValidationError> {
    if limit >= SEARCH_GUILD_MEMBERS_LIMIT_MIN && limit <= SEARCH_GUILD_MEMBERS_LIMIT_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::SearchGuildMembers { limit },
        })
    }
}

/// Ensure that the stage instance's topic length is correct.
///
/// The length must be at least [`STAGE_TOPIC_LENGTH_MIN`] and at most
/// [`STAGE_TOPIC_LENGTH_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`StageTopic`] if the length is invalid.
///
/// [`StageTopic`]: ValidationErrorType::StageTopic
/// [this documentation entry]: https://discord.com/developers/docs/resources/stage-instance#stage-instance-object
pub fn stage_topic(topic: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = topic.as_ref().chars().count();

    if (STAGE_TOPIC_LENGTH_MIN..=STAGE_TOPIC_LENGTH_MAX).contains(&len) {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::StageTopic { len },
        })
    }
}

/// Ensure that a guild template's description length is correct.
///
/// The length must be at most [`TEMPLATE_DESCRIPTION_LENGTH_MAX`]. This is
/// based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`TemplateDescription`] if the length is invalid.
///
/// [`TemplateDescription`]: ValidationErrorType::TemplateDescription
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-template#guild-template-object-guild-template-structure
pub fn template_description(description: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = description.as_ref().chars().count();

    if len <= TEMPLATE_DESCRIPTION_LENGTH_MAX {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::TemplateDescription { len },
        })
    }
}

/// Ensure that a guild template's name length is correct.
///
/// The length must be at least [`TEMPLATE_NAME_LENGTH_MIN`] and at most
/// [`TEMPLATE_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`TemplateName`] if the length is invalid.
///
/// [`TemplateName`]: ValidationErrorType::TemplateName
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-template#guild-template-object-guild-template-structure
pub fn template_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = name.as_ref().chars().count();

    if (TEMPLATE_NAME_LENGTH_MIN..=TEMPLATE_NAME_LENGTH_MAX).contains(&len) {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::TemplateName { len },
        })
    }
}

/// Ensure that the username length is correct.
///
/// The length must be at least [`USERNAME_LIMIT_MIN`] and at most
/// [`USERNAME_LIMIT_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`Username`] if the length is invalid.
///
/// [`Username`]: ValidationErrorType::Username
/// [this documentation entry]: https://discord.com/developers/docs/resources/user#usernames-and-nicknames
pub fn username(value: impl AsRef<str>) -> Result<(), ValidationError> {
    let len = value.as_ref().chars().count();

    if (USERNAME_LIMIT_MIN..=USERNAME_LIMIT_MAX).contains(&len) {
        Ok(())
    } else {
        Err(ValidationError {
            kind: ValidationErrorType::Username { len },
        })
    }
}

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

    #[test]
    fn test_create_guild_ban_delete_message_days() {
        assert!(create_guild_ban_delete_message_days(0).is_ok());
        assert!(create_guild_ban_delete_message_days(1).is_ok());
        assert!(create_guild_ban_delete_message_days(7).is_ok());

        assert!(create_guild_ban_delete_message_days(8).is_err());
    }

    #[test]
    fn test_communication_disabled_until() {
        #[allow(clippy::cast_possible_wrap)]
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        let ok_timestamp =
            Timestamp::from_secs(now + COMMUNICATION_DISABLED_MAX_DURATION - 1000).unwrap();
        assert!(communication_disabled_until(ok_timestamp).is_ok());

        let err_timestamp =
            Timestamp::from_secs(now + COMMUNICATION_DISABLED_MAX_DURATION + 1000).unwrap();
        assert!(communication_disabled_until(err_timestamp).is_err());
    }

    #[test]
    fn test_get_channel_messages_limit() {
        assert!(get_channel_messages_limit(1).is_ok());
        assert!(get_channel_messages_limit(100).is_ok());

        assert!(get_channel_messages_limit(0).is_err());
        assert!(get_channel_messages_limit(101).is_err());
    }

    #[test]
    fn test_get_current_user_guilds_limit() {
        assert!(get_current_user_guilds_limit(1).is_ok());
        assert!(get_current_user_guilds_limit(200).is_ok());

        assert!(get_current_user_guilds_limit(0).is_err());
        assert!(get_current_user_guilds_limit(201).is_err());
    }

    #[test]
    fn test_get_audit_log_limit() {
        assert!(get_guild_audit_log_limit(1).is_ok());
        assert!(get_guild_audit_log_limit(100).is_ok());

        assert!(get_guild_audit_log_limit(0).is_err());
        assert!(get_guild_audit_log_limit(101).is_err());
    }

    #[test]
    fn test_get_guild_members_limit() {
        assert!(get_guild_members_limit(1).is_ok());
        assert!(get_guild_members_limit(1000).is_ok());

        assert!(get_guild_members_limit(0).is_err());
        assert!(get_guild_members_limit(1001).is_err());
    }

    #[test]
    fn test_get_reactions_limit() {
        assert!(get_reactions_limit(1).is_ok());
        assert!(get_reactions_limit(100).is_ok());

        assert!(get_reactions_limit(0).is_err());
        assert!(get_reactions_limit(101).is_err());
    }

    #[test]
    fn test_guild_name() {
        assert!(guild_name("aa").is_ok());
        assert!(guild_name("a".repeat(100)).is_ok());

        assert!(guild_name("").is_err());
        assert!(guild_name("a").is_err());
        assert!(guild_name("a".repeat(101)).is_err());
    }

    #[test]
    fn test_guild_prune_days() {
        assert!(guild_prune_days(1).is_ok());
        assert!(guild_prune_days(30).is_ok());

        assert!(guild_prune_days(0).is_err());
        assert!(guild_prune_days(31).is_err());
        assert!(guild_prune_days(100).is_err());
    }

    #[test]
    fn test_invite_max_age() {
        assert!(invite_max_age(0).is_ok());
        assert!(invite_max_age(86_400).is_ok());
        assert!(invite_max_age(604_800).is_ok());

        assert!(invite_max_age(604_801).is_err());
    }

    #[test]
    fn test_invite_max_uses() {
        assert!(invite_max_uses(0).is_ok());
        assert!(invite_max_uses(100).is_ok());

        assert!(invite_max_uses(101).is_err());
    }

    #[test]
    fn test_nickname() {
        assert!(nickname("a").is_ok());
        assert!(nickname("a".repeat(32)).is_ok());

        assert!(nickname("").is_err());
        assert!(nickname("a".repeat(33)).is_err());
    }

    #[test]
    fn test_scheduled_event_description() {
        assert!(scheduled_event_description("a").is_ok());
        assert!(scheduled_event_description("a".repeat(1000)).is_ok());

        assert!(scheduled_event_description("").is_err());
        assert!(scheduled_event_description("a".repeat(1001)).is_err());
    }

    #[test]
    fn test_scheduled_event_name() {
        assert!(scheduled_event_name("a").is_ok());
        assert!(scheduled_event_name("a".repeat(100)).is_ok());

        assert!(scheduled_event_name("").is_err());
        assert!(scheduled_event_name("a".repeat(101)).is_err());
    }

    #[test]
    fn test_search_guild_members_limit() {
        assert!(search_guild_members_limit(1).is_ok());
        assert!(search_guild_members_limit(1000).is_ok());

        assert!(search_guild_members_limit(0).is_err());
        assert!(search_guild_members_limit(1001).is_err());
    }

    #[test]
    fn test_stage_topic() {
        assert!(stage_topic("a").is_ok());
        assert!(stage_topic("a".repeat(120)).is_ok());

        assert!(stage_topic("").is_err());
        assert!(stage_topic("a".repeat(121)).is_err());
    }

    #[test]
    fn test_template_description() {
        assert!(template_description("").is_ok());
        assert!(template_description("a").is_ok());
        assert!(template_description("a".repeat(120)).is_ok());

        assert!(template_description("a".repeat(121)).is_err());
    }

    #[test]
    fn test_template_name() {
        assert!(template_name("a").is_ok());
        assert!(template_name("a".repeat(100)).is_ok());

        assert!(template_name("").is_err());
        assert!(template_name("a".repeat(101)).is_err());
    }

    #[test]
    fn test_username() {
        assert!(username("aa").is_ok());
        assert!(username("a".repeat(32)).is_ok());

        assert!(username("a").is_err());
        assert!(username("a".repeat(33)).is_err());
    }
}