rrhodium 1.0.0

Lib for building modrinth API getters urls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
//! # rrhodium
//! *rrhodium* is a library focused in building urls for the modrinth API. Since it is a pain in
//! the ~ass~ to make them and specially the facets.
//!
//!
//! # Builder approach
//!
//! The approach for **bulding** the urls is a **BUILDER** pattern (who could tell?), which I
//! think it's very nice. Also it is implemented with *manual* type-state so you can't fuck it up
//! and build urls without specifying a search type.
//!
//! ```ignore
//! use rrhodium::*;
//!
//! fn buzz() {
//!     SearchBuilder::new().game_versions(vec!["1.19.2", "1.19.1"]).build_url()
//! }
//! ```
//! The above code **WON'T** compile, since it's mising the search type.
//!
//! # Facets approach
//!
//! For the facets this library approachs the problem by using two structs:
//! `FacetsConjunction` and `FacetsDisjunction`, since they must be added in
//! [CNF](<https://en.wikipedia.org/wiki/Conjunctive_normal_form>) way.
//!
//! ```no_run
//! use rrhodium::*;
//! fn foo() -> FacetsConjunction {
//! FacetsConjunction::new()
//!     .and(FacetsDisjunction::new_with(Facets::Categories("Technology".to_string())))
//!     .and(FacetsDisjunction::new_with(Facets::Categories("Magic".to_string())))
//!     .and(
//!         FacetsDisjunction::new_with(Facets::Version("1.19".to_string()))
//!             .or(Facets::Version("1.19.1".to_string())),
//!     )
//! }
//! ```
//!
//! The above example means:
//!
//! I want my search to show (whatever you are searching) only results which categories are
//! "Technology" **AND** "Magic", **AND** the version must be 1.19 **OR** 1.19.1.
//!
//! Whatever is inside of every disjunction is an **OR** and everything that is inside a conjuntion
//! is an **AND**.
//!
//!
//! For now only the getters routes are provided, and I don't think I'll add the others
//! (create/delete/modify project)

use itertools::Itertools;
use std::fmt::{Display, Formatter, Write};

/// A type for representing that no search type is set.
type NoSearchType = ();

#[derive(Clone, Debug)]
pub enum HashingAlgo {
    Sha1,
    Sha512,
}

impl Display for HashingAlgo {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sha1 => write!(f, "sha1"),
            Self::Sha512 => write!(f, "sha512"),
        }
    }
}

/// A list specifying the different kinds of requirements types.
/// - Optional
/// - Required
/// - Unsupported
#[derive(Debug, Copy, Clone)]
pub enum Requirement {
    Optional,
    Required,
    Unsupported,
}

impl Display for Requirement {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Optional => "optional",
            Self::Required => "required",
            Self::Unsupported => "unsupported",
        };
        write!(f, "{s}")
    }
}

/// A list specifying the different kinds of requests based on the API
/// routes.
#[derive(Debug, Clone)]
pub enum SearchType {
    /// Search projects
    ///
    /// /search
    ///
    /// It's recommended to build this variant through the [`QueryBuilder`] struct.
    Search {
        query: String,
        limit: Option<u32>,
        offset: Option<u32>,
    },

    // Get a project
    //
    /// /project
    Project { id: String },

    /// Get multiple projects
    ///
    /// /projects
    MultiProject { ids: Vec<&'static str> },

    /// Get all of a project's dependencies
    ///
    /// /project/{id|slug}/dependencies
    Dependencies { id: String },

    /// List project's versions
    ///
    /// /project/{id|slug}/version
    ///
    /// - loaders: The types of loaders to filter for.
    ProjectVersion {
        id: String,
        loaders: Option<Vec<String>>,
    },

    /// Get a version
    ///
    /// /version/{id}
    ///
    /// - id: The ID of the version
    Version { id: String },

    /// Get a version given a version number or ID
    ///
    /// Please note that, if the version number provided matches multiple versions, only the oldest
    /// matching version will be returned.
    ///
    /// Missing :(

    /// Get multiple versions
    ///
    /// /versions
    ///
    /// -ids The IDs of the versions
    ProjectVersions { ids: Vec<String> },

    /// Get version from hash
    ///
    /// /version_file/{hash}
    VersionFile { hash: String, algo: HashingAlgo },

    /// Latest version of a project from a hash, loader(s), and game version(s)
    ///
    /// /version_file/{hash}/update
    VersionFileUpdate { hash: String, algo: HashingAlgo },

    /// Get versions from hashes
    ///
    /// /version_files
    ///
    /// The hashes [**must** be in the body](https://docs.modrinth.com/api/operations/versionsfromhashes/) of the request
    VersionFiles,

    /// Latest versions of multiple project from hashes, loader(s), and game version(s)
    ///
    /// /version_files/update
    ///
    /// The hashes [**must** be in the body](https://docs.modrinth.com/api/operations/getlatestversionsfromhashes/) of the request
    VersionFilesUpdate,

    /// /tag/category
    Categories,

    /// /tag/loader
    Loaders,

    /// /tag/game_version
    GameVersions,

    /// /tag/project_type
    ProjectTypes,
}

impl Display for SearchType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            SearchType::Project { id } => write!(f, "project/{id}?"),
            SearchType::MultiProject { ids } => {
                let ids = ids
                    .iter()
                    .map(|id| format!("\"{id}\""))
                    .collect::<Vec<String>>()
                    .join(",");

                write!(f, "projects?ids=[{ids}]")
            }
            SearchType::Search { .. } => write!(f, "search"),
            SearchType::VersionFile { hash, .. } => write!(f, "version_file/{hash}"),
            SearchType::VersionFiles => write!(f, "version_files"),
            SearchType::Dependencies { id } => write!(f, "project/{id}/dependencies"),
            SearchType::ProjectVersion { id, .. } => write!(f, "project/{id}/version"),
            SearchType::ProjectVersions { ids } => {
                let ids = ids
                    .iter()
                    .map(|id| format!("\"{id}\""))
                    .collect::<Vec<String>>()
                    .join(",");

                write!(f, "versions?ids=[{ids}]")
            }
            SearchType::Version { id } => write!(f, "version/{id}"),
            SearchType::Categories => write!(f, "tag/category"),
            SearchType::Loaders => write!(f, "tag/loader"),
            SearchType::VersionFileUpdate { hash, .. } => write!(f, "version_file/{hash}/update"),
            SearchType::VersionFilesUpdate => write!(f, "/version_files/update"),
            SearchType::GameVersions => write!(f, "/tag/game_version"),
            SearchType::ProjectTypes => write!(f, "/tag/project_type"),
        }
    }
}

/// A builder for constructing [`SearchType::Search`] instances with optional parameters.
///
/// This builder provides a fluent interface for creating search queries with customizable
/// search terms, result limits, and pagination offsets. All parameters are optional,
/// allowing for flexible search construction.
///
/// # Examples
///
/// Basic search with just a query:
///
/// ```rust
/// use rrhodium::QueryBuilder;
///
/// let search = QueryBuilder::new()
///     .query("minecraft mods")
///     .build();
/// ```
/// # Default Behavior
///
/// - **Query**: Empty string (searches all content)
/// - **Limit**: Determined by the API default (typically 10-20 results)
/// - **Offset**: 0 (starts from the first result)
#[derive(Default)]
pub struct QueryBuilder {
    query: Option<String>,
    limit: Option<u32>,
    offset: Option<u32>,
}

impl QueryBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    // Sets the search query string.
    ///
    /// The query string is used to search for content matching the specified terms.
    /// Different APIs may support various query syntaxes (e.g., phrase matching,
    /// boolean operators, wildcards).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::QueryBuilder;
    /// let search = QueryBuilder::new()
    ///     .query("sodium")
    ///     .build();
    /// ```
    ///
    /// With a dynamically generated query:
    ///
    /// ```rust
    /// # use rrhodium::QueryBuilder;
    /// let user_input = "adventure";
    /// let search = QueryBuilder::new()
    ///     .query(format!("{} mods", user_input))
    ///     .build();
    /// ```
    ///
    /// # Parameters
    ///
    /// * `query` - The search terms. Accepts anything that implements `Into<String>`
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    /// Sets the maximum number of results to return.
    ///
    /// This parameter controls how many search results will be returned in a single
    /// response. Useful for controlling response size and implementing pagination.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::QueryBuilder;
    /// let search = QueryBuilder::new()
    ///     .limit(50)
    ///     .build();
    /// ```
    ///
    /// # Parameters
    ///
    /// * `limit` - Maximum number of results to return. Must be positive.
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Notes
    ///
    /// The actual maximum limit may be constrained by the API server. Very large
    /// limits might be reduced to prevent performance issues.
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Sets the number of results to skip (pagination offset).
    ///
    /// This parameter is used for pagination by skipping the specified number of results from the
    /// beginning. Combined with `limit`, it enables pagination through large result sets.
    ///
    /// # Examples
    ///
    /// Getting the second page of results (assuming 20 results per page):
    ///
    /// ```rust
    /// # use rrhodium::QueryBuilder;
    /// let page_2 = QueryBuilder::new()
    ///     .query("popular mods")
    ///     .limit(20)
    ///     .offset(20)  // Skip first 20 results
    ///     .build();
    /// ```
    ///
    /// # Parameters
    ///
    /// * `offset` - Number of results to skip from the beginning
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Builds the final [`SearchType::Search`] instance.
    ///
    /// Consumes the builder and creates a `SearchType::Search` with the configured
    /// parameters. Any unset optional parameters will use their default values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::{SearchBuilder, QueryBuilder};
    /// let search = QueryBuilder::new()
    ///     .query("minecraft")
    ///     .limit(25)
    ///     .offset(10)
    ///     .build();
    ///
    ///
    /// assert_eq!(
    ///     "https://api.modrinth.com/v2/search?query=\"minecraft\"&limit=25&offset=10",
    ///     SearchBuilder::new().search_type(search).build_url()
    /// );
    /// ```
    ///
    /// # Returns
    ///
    /// A configured `SearchType::Search` instance ready for use
    pub fn build(self) -> SearchType {
        SearchType::Search {
            query: self.query.unwrap_or_default(), // Empty string if no query provided
            limit: self.limit,
            offset: self.offset,
        }
    }
}

/// A builder for building the URL with the indicated parameters
/// This struct works with `TypeState` Programming so the [`SearchBuilder::build_url()`] method
/// can't be called unless `search_type` is set.
///
/// The `facets` field works as a conjunction (AND) of disjunctions (OR):
#[derive(Default)]
pub struct SearchBuilder<T = NoSearchType> {
    search_type: T,
    facets: Option<FacetsConjunction>,
    game_versions: Vec<String>,
}

impl SearchBuilder<NoSearchType> {
    #[must_use]
    pub fn new() -> SearchBuilder<NoSearchType> {
        SearchBuilder::default()
    }
}

impl<T> SearchBuilder<T> {
    /// Sets the facets.
    #[must_use]
    pub fn facets(mut self, facets: impl Into<FacetsConjunction>) -> Self {
        self.facets = Some(facets.into());
        self
    }

    /// Sets the game versions filter for the project version search.
    ///
    ///
    /// # Parameters
    ///
    /// - `versions`: A type that can be iterated and its items implements `ToString`.
    ///
    /// # Returns
    ///
    /// Returns an updated instance of the `SearchBuilder` with the specified
    /// game versions filter applied.
    ///
    /// # Example
    ///
    /// ```rust no_run
    /// use rrhodium::*;
    /// # fn foo() {
    /// let builder = SearchBuilder::new()
    ///     .search_type(SearchType::ProjectVersion {id: "example_id".to_owned(), loaders:
    ///     Some(vec!["fabric".to_string()])})
    ///     .game_versions(["1.16.5", "1.17.1"])
    ///     .build_url();
    /// # }
    /// ```
    ///
    /// # Restrictions
    ///
    /// This method is only available when the search type is `ProjectVersion`.
    /// Attempting to call this method for other search types will do nothing.
    ///
    /// # Panics
    ///
    /// This method does not panic.
    ///
    /// # Notes
    ///
    /// - The `game_versions` parameter allows you to filter results to only
    ///   include project versions compatible with the specified game versions.
    /// - Ensure that you are using this method within the `ProjectVersion`
    ///   search context, as it is specifically designed for filtering versions
    ///   based on game compatibility.
    #[must_use]
    pub fn game_versions<E>(mut self, versions: impl IntoIterator<Item = E>) -> Self
    where
        E: ToString,
    {
        self.game_versions = versions.into_iter().map(|x| x.to_string()).collect();
        self
    }

    /// Adds a single game version to the game versions filter for the project
    /// version search.
    ///
    /// This method allows you to append a game version to the existing filter
    /// criteria in the `SearchBuilder`. The version is added to the vector
    /// of game versions that will be used to filter the results of the
    /// search.
    ///
    /// # Parameters
    ///
    /// - `version`: Whatever type that can be transformed into a `String`.
    ///
    /// # Returns
    ///
    /// Returns an updated instance of the `SearchBuilder` with the specified
    /// game version added to the filter criteria.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rrhodium::{SearchType, SearchBuilder};
    /// let builder = SearchBuilder::new()
    ///     .search_type(SearchType::ProjectVersion {id: "example_id".to_string(), loaders: Some(vec!["fabric".to_string()])})
    ///     .add_game_version("1.16.5")
    ///     .add_game_version("1.17.1")
    ///     .build_url();
    /// ```
    ///
    /// # Restrictions
    ///
    /// This method only has an effect when the search type is `ProjectVersion`.
    /// If used with a different search type, it will have no impact on the
    /// search builder and will silently ignore the call.
    ///
    /// # Panics
    ///
    /// This method does not panic.
    ///
    /// # Errors
    ///
    /// This method does not return errors.
    ///
    /// # Notes
    /// - Ensure that this method is called within the `ProjectVersion` search
    ///   context, as it is specifically designed for filtering project versions
    ///   based on game compatibility.
    /// - If used outside the `ProjectVersion` context, the method will not
    ///   modify the builder and will effectively do nothing.
    #[must_use]
    pub fn add_game_version(mut self, version: impl ToString) -> Self {
        self.game_versions.push(version.to_string());
        self
    }

    pub fn search_type(self, search_type: SearchType) -> SearchBuilder<SearchType> {
        SearchBuilder {
            search_type,
            facets: self.facets,
            game_versions: self.game_versions,
        }
    }
}

impl SearchBuilder<SearchType> {
    /// Generates the URL based on the `SearchBuilder` object.
    ///
    /// This method constructs a URL for the Modrinth API using various
    /// parameters from the `SearchBuilder` struct. It supports multiple
    /// search types and query parameters, and it constructs the URL
    /// accordingly.
    ///
    /// # Returns
    ///
    /// A `String` representing the constructed URL.
    ///
    /// # Examples
    ///
    /// ```rust no_run
    /// use rrhodium::*;
    /// # fn foo() {
    ///     let search_builder: String = SearchBuilder::new()
    ///     .search_type(QueryBuilder::new().limit(10).offset(5).build())
    ///     .build_url();
    /// assert_eq!("https://api.modrinth.com/v2/search?limit=10&offset=5", &search_builder);
    /// # }
    /// ```
    #[must_use]
    pub fn build_url(self) -> String {
        // Don't you like my unwraps ? I don't like you either dw ;)
        let mut url: String = "https://api.modrinth.com/v2/".to_string();
        write!(url, "{}", self.search_type).unwrap();

        let mut is_first = true;
        let add_param = |url: &mut String, is_first: &mut bool| {
            if *is_first {
                url.push('?');
                *is_first = false;
            } else {
                url.push('&');
            }
        };

        match &self.search_type {
            SearchType::Categories
            | SearchType::Loaders
            | SearchType::GameVersions
            | SearchType::ProjectTypes => {}

            SearchType::Search {
                query,
                limit,
                offset,
            } => {
                if !query.is_empty() {
                    add_param(&mut url, &mut is_first);
                    write!(url, "query=\"{query}\"").unwrap();
                }
                if let Some(limit) = limit {
                    add_param(&mut url, &mut is_first);
                    write!(url, "limit={limit}").unwrap();
                }
                if let Some(offset) = offset {
                    add_param(&mut url, &mut is_first);
                    write!(url, "offset={offset}").unwrap();
                }
                if self.facets.as_ref().is_some_and(|f| !f.is_empty()) {
                    add_param(&mut url, &mut is_first);
                    self.add_facets(&mut url);
                }
            }
            SearchType::ProjectVersion { loaders, .. } => {
                let versions = self
                    .game_versions
                    .iter()
                    .map(|v| format!("\"{v}\""))
                    .join(",");
                add_param(&mut url, &mut is_first);
                write!(url, "game_versions=[{versions}]").unwrap();

                if let Some(loaders) = loaders {
                    let loaders = loaders.iter().map(|v| format!("\"{v}\"")).join(",");
                    add_param(&mut url, &mut is_first);
                    write!(url, "loaders=[{loaders}]").unwrap();
                }
            }
            SearchType::VersionFile { algo, .. } | SearchType::VersionFileUpdate { algo, .. } => {
                add_param(&mut url, &mut is_first);
                write!(url, "algorithm={algo}").unwrap();
            }
            _ => {}
        }

        url
    }

    fn add_facets(&self, url: &mut String) {
        if let Some(ref facets) = self.facets {
            let facets_str = facets
                .iter()
                .map(|conjunction| format!("[{}]", conjunction.facets.iter().join(",")))
                .join(",");

            write!(url, "facets=[{facets_str}]").unwrap();
        }
    }
}

/// A collection of disjunctions that represents a logical AND operation (conjunction).
///
/// This struct combines multiple [`FacetsDisjunction`]s where **all** of them must be
/// satisfied for a search result to match. Each disjunction within the conjunction
/// represents an OR operation, creating complex logical expressions.
///
/// The logical structure follows the pattern: `(A ∨ B ∨ C) ∧ (D ∨ E) ∧ (F)`
/// where ∨ represents OR and ∧ represents AND.
///
/// ```rust
/// use rrhodium::{FacetsConjunction, FacetsDisjunction, Facets};
///
/// let version_filter = FacetsDisjunction::new_with(Facets::Version("1.19".to_string()))
///     .or(Facets::Version("1.19.1".to_string()))
///     .or(Facets::Version("1.19.2".to_string()));
///
/// let category_filter = FacetsDisjunction::new_with(Facets::Categories("technology".to_string()))
///     .or(Facets::Categories("magic".to_string()));
///
/// let search_filter = FacetsConjunction::new()
///     .and(version_filter)
///     .and(category_filter);
/// ```
///
/// # Into friendly
///
/// You can create a `FacetsConjunction` from various sources:
///
/// ```rust
/// use rrhodium::*;
///
/// let disjunctions = vec![
///     FacetsDisjunction::new().or(Facets::Version("1.19".to_string())),
///     FacetsDisjunction::new_with(Facets::Categories("Technology".to_string())),
/// ];
///
/// let conjunction: FacetsConjunction = disjunctions.into();
/// ```
///
/// # Iterator friendly
///
/// ```rust
/// use rrhodium::*;
///
/// let categories = vec!["Technology", "Magic", "Adventure"];
///
/// let x: FacetsConjunction = categories.iter()
///     .map(|c| FacetsDisjunction::new_with(Facets::Categories(c.to_string())))
///     .collect();
/// ```
///
/// # Search Logic
///
/// In search queries, this conjunction ensures that:
/// - **ALL** disjunctions must be satisfied
/// - Within each disjunction, **ANY ONE** of the facets can match
/// - Results must match every constraint group simultaneously
///
#[derive(Debug, Clone, Default)]
pub struct FacetsConjunction {
    disjunctions: Vec<FacetsDisjunction>,
}

impl FacetsConjunction {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn new_with(dist: FacetsDisjunction) -> Self {
        Self::default().and(dist)
    }

    // Adds a disjunction to this conjunction using a builder pattern.
    ///
    /// This method consumes `self` and returns a new instance with the disjunction added,
    /// allowing for method chaining. The added disjunction becomes an additional
    /// requirement that must be satisfied along with all existing disjunctions.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::{FacetsConjunction, FacetsDisjunction, Facets};
    /// let version_filter = FacetsDisjunction::new_with(Facets::Version("1.19".to_string()));
    ///
    /// let category_filter = FacetsDisjunction::new_with(Facets::Categories("technology".to_string()));
    ///
    /// let conjunction = FacetsConjunction::new()
    ///     .and(version_filter)
    ///     .and(category_filter);
    /// ```
    ///
    /// # Parameters
    ///
    /// * `disj` - The disjunction to add to this conjunction
    ///
    /// # Returns
    ///
    /// A new `FacetsConjunction` instance with the added disjunction
    #[must_use]
    pub fn and(mut self, disj: FacetsDisjunction) -> Self {
        self.disjunctions.push(disj);
        self
    }

    /// Returns `true` if this conjunction contains no disjunctions.
    ///
    /// An empty conjunction typically matches all results since there are
    /// no constraints to satisfy.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::{FacetsConjunction, FacetsDisjunction, Facets};
    /// let empty = FacetsConjunction::new();
    /// assert!(empty.is_empty());
    ///
    /// let non_empty = FacetsConjunction::new().and(FacetsDisjunction::new_with(Facets::Version("1.19".to_string())));
    /// assert!(!non_empty.is_empty());
    /// ```
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.disjunctions.is_empty()
    }

    /// Returns an iterator over the disjunctions in this conjunction.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::{FacetsConjunction, FacetsDisjunction, Facets};
    /// let conjunction = FacetsConjunction::new()
    ///     .and(FacetsDisjunction::new_with(Facets::Version("1.19".to_string())))
    ///     .and(FacetsDisjunction::new_with(Facets::Categories("tech".to_string())));
    ///
    /// for disjunction in conjunction.iter() {
    ///     println!("Disjunction with {} facets", disjunction);
    /// }
    /// ```
    pub fn iter(&self) -> std::slice::Iter<'_, FacetsDisjunction> {
        self.disjunctions.as_slice().iter()
    }
}

impl<'a> IntoIterator for &'a FacetsConjunction {
    type Item = &'a FacetsDisjunction;
    type IntoIter = std::slice::Iter<'a, FacetsDisjunction>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl IntoIterator for FacetsConjunction {
    type Item = FacetsDisjunction;
    type IntoIter = std::vec::IntoIter<FacetsDisjunction>;
    fn into_iter(self) -> Self::IntoIter {
        self.disjunctions.into_iter()
    }
}

impl std::convert::From<Vec<FacetsDisjunction>> for FacetsConjunction {
    fn from(value: Vec<FacetsDisjunction>) -> Self {
        Self {
            disjunctions: value,
        }
    }
}

impl std::iter::FromIterator<FacetsDisjunction> for FacetsConjunction {
    fn from_iter<T: IntoIterator<Item = FacetsDisjunction>>(iter: T) -> Self {
        Self {
            disjunctions: iter.into_iter().collect(),
        }
    }
}

/// A collection of facets that represents a logical OR operation (disjunction).
///
/// This struct is used to group multiple [`Facets`] together where any one of them
/// can match the search criteria. When used in a search query, at least one of
/// the contained facets must be satisfied for a result to match.
///
/// # Search Logic
///
/// In the context of search queries, this disjunction works as follows:
/// - **1.19.0 OR 1.19.1**: Returns projects compatible with either version
/// - **Technology OR Adventure**: Returns projects in either category
/// - **Forge OR Fabric**: Returns projects supporting either mod loader
///
/// # Into friendly
///
/// You can create a `FacetsDisjunction` from a vector of `Facets`, no extra allocations! :
/// ```rust
/// # use rrhodium::{FacetsDisjunction, Facets};
/// # fn bar() {
/// let facets = vec![
///     Facets::Version("1.19".to_string()),
///     Facets::Version("1.19.1".to_string()),
///     Facets::Categories("Technology".to_string()),
/// ];
///
/// let disjunction: FacetsDisjunction = facets.into();
/// # }
/// ```
///
/// # Iterator friendly
///
/// ```rust
/// # use rrhodium::{FacetsDisjunction, Facets};
/// # fn foo() {
/// // Create facets from a range of versions
/// let version_facets = (0..3)
///     .map(|i| Facets::Version(format!("1.19.{}", i)));
///
/// // Create a disjunction from the version facets iterator, no need to collect !
/// let version_disjunction: FacetsDisjunction = version_facets.into_iter().collect();
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct FacetsDisjunction {
    facets: Vec<Facets>,
}

impl FacetsDisjunction {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn new_with(facet: Facets) -> Self {
        Self::default().or(facet)
    }

    /// Adds a facet to this disjunction by mutating the current instance.
    ///
    /// This method modifies the disjunction in place. For a builder-style
    /// approach that doesn't require mutability, see [`or`](Self::or).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::{FacetsDisjunction, Facets};
    /// let mut disjunction = FacetsDisjunction::new_with(Facets::Version("1.19.0".to_string()));
    /// disjunction.push(Facets::Version("1.19.1".to_string()));
    /// ```
    ///
    pub fn push(&mut self, facet: Facets) {
        self.facets.push(facet);
    }

    /// Adds a facet to this disjunction using a builder pattern.
    ///
    /// This method consumes `self` and returns a new instance with the facet added,
    /// allowing for method chaining without requiring mutability.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rrhodium::{FacetsDisjunction, Facets};
    /// let disjunction = FacetsDisjunction::new_with(Facets::Categories("technology".to_string()))
    ///     .or(Facets::Categories("adventure".to_string()))
    ///     .or(Facets::Categories("utility".to_string()));
    /// ```
    /// # Returns
    ///
    /// A new `FacetsDisjunction` instance with the added facet.
    #[must_use]
    pub fn or(mut self, facet: Facets) -> Self {
        self.push(facet);
        self
    }

    pub fn iter(&self) -> std::slice::Iter<'_, Facets> {
        self.facets.as_slice().iter()
    }
}

impl Display for FacetsDisjunction {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = self.facets.iter().map(|f| f.to_string()).join("v");
        write!(f, "{s}")
    }
}

impl<'a> IntoIterator for &'a FacetsDisjunction {
    type Item = &'a Facets;
    type IntoIter = std::slice::Iter<'a, Facets>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl IntoIterator for FacetsDisjunction {
    type Item = Facets;
    type IntoIter = std::vec::IntoIter<Facets>;

    fn into_iter(self) -> Self::IntoIter {
        self.facets.into_iter()
    }
}

impl std::convert::From<Vec<Facets>> for FacetsDisjunction {
    fn from(value: Vec<Facets>) -> Self {
        Self { facets: value }
    }
}

impl std::iter::FromIterator<Facets> for FacetsDisjunction {
    fn from_iter<T: IntoIterator<Item = Facets>>(iter: T) -> Self {
        Self {
            facets: iter.into_iter().collect(),
        }
    }
}

/// A list specifying the different kinds of facets/filters that can be applied
/// to queries.
#[derive(Debug, Clone)]
pub enum Facets {
    ProjectType(String),
    Categories(String),
    Version(String),
    ClientSide(Requirement),
    ServerSide(Requirement),
    OpenSource,
}

impl Display for Facets {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Facets::ProjectType(t) => format!("\"project_type:{t}\""),
            Facets::Categories(c) => format!("\"categories:{c}\""),
            Facets::Version(v) => format!("\"versions:{v}\""),
            Facets::ClientSide(r) => format!("\"client_side:{r}\""),
            Facets::ServerSide(r) => format!("\"server_side:{r}\""),
            Facets::OpenSource => todo!(),
        };
        f.write_str(s.as_str())
    }
}

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

    #[test]
    pub fn search_builder() {
        let search_type = QueryBuilder::new().limit(5).offset(10).build();

        let url = SearchBuilder::new().search_type(search_type).build_url();

        assert_eq!("https://api.modrinth.com/v2/search?limit=5&offset=10", url)
    }

    #[test]
    pub fn search_builder_facets() {
        let versions_facets = FacetsDisjunction::new_with(Facets::Version("1.21".to_string()))
            .or(Facets::Version("1.20".to_string()));

        let url = SearchBuilder::new()
            .facets(vec![versions_facets])
            .search_type(QueryBuilder::new().offset(10).limit(5).build())
            .build_url();
        assert_eq!(
            "https://api.modrinth.com/v2/search?limit=5&offset=10&facets=[\
                [\"versions:1.21\",\"versions:1.20\"]\
            ]",
            url
        );
    }

    #[test]
    pub fn search_builder_facets_disjunction() {
        let mut versions_facets = FacetsDisjunction::new_with(Facets::Version("1.21".to_string()));
        versions_facets.push(Facets::Version("1.20".to_string()));

        let type_facets = FacetsDisjunction::new_with(Facets::ProjectType("modpack".to_string()));

        let url = SearchBuilder::new()
            .facets(vec![versions_facets, type_facets])
            .search_type(QueryBuilder::new().offset(10).limit(5).build())
            .build_url();

        assert_eq!(
            "https://api.modrinth.com/v2/search?limit=5&offset=10&facets=[\
                [\"versions:1.21\",\"versions:1.20\"],\
                [\"project_type:modpack\"]\
            ]",
            url
        );
    }

    #[test]
    pub fn search_builder_facets_disjunction_builder() {
        let facets = FacetsConjunction::new()
            .and(
                FacetsDisjunction::new_with(Facets::Version("1.19".to_string()))
                    .or(Facets::Version("1.22".to_string())),
            )
            .and(FacetsDisjunction::new_with(Facets::ProjectType(
                "modpack".to_string(),
            )))
            .and(
                FacetsDisjunction::new_with(Facets::Categories("technology".to_string()))
                    .or(Facets::Categories("adventure".to_string())),
            );

        let url = SearchBuilder::new()
            .facets(facets)
            .search_type(QueryBuilder::new().offset(10).limit(5).build())
            .build_url();

        assert_eq!(
            "https://api.modrinth.com/v2/search?limit=5&offset=10&facets=[\
                [\"versions:1.19\",\"versions:1.22\"],\
                [\"project_type:modpack\"],\
                [\"categories:technology\",\"categories:adventure\"]\
            ]",
            url
        );
    }

    #[test]
    pub fn search_builder_projects() {
        let url = SearchBuilder::new()
            .search_type(SearchType::MultiProject {
                ids: vec!["AAA", "BBB"],
            })
            .build_url();

        assert_eq!(
            "https://api.modrinth.com/v2/projects?ids=[\"AAA\",\"BBB\"]",
            url
        )
    }

    #[test]
    pub fn search_builder_project_versions() {
        let url = SearchBuilder::new()
            .search_type(SearchType::ProjectVersion {
                id: "Jw3Wx1KR".to_string(),
                loaders: None,
            })
            .game_versions(["1.18", "1.18.2"])
            .build_url();

        assert_eq!(
            "https://api.modrinth.com/v2/project/Jw3Wx1KR/version?game_versions=[\"1.18\",\"1.18.2\"]",
            url
        );
    }

    #[test]
    pub fn search_builder_project_versions_one_loader() {
        let url = SearchBuilder::new()
            .search_type(SearchType::ProjectVersion {
                id: "Jw3Wx1KR".to_string(),
                loaders: Some(vec!["fabric".to_string()]),
            })
            .game_versions(["1.18", "1.18.2"])
            .build_url();

        assert_eq!(
            "https://api.modrinth.com/v2/project/Jw3Wx1KR/version?game_versions=[\"1.18\",\"1.18.2\"]&loaders=[\"fabric\"]",
            url
        );
    }

    #[test]
    pub fn search_builder_project_versions_two_loaders() {
        let url = SearchBuilder::new()
            .search_type(SearchType::ProjectVersion {
                id: "Jw3Wx1KR".to_string(),
                loaders: Some(vec!["fabric".to_string(), "quilt".to_string()]),
            })
            .game_versions(["1.18", "1.18.2"])
            .build_url();

        assert_eq!(
            "https://api.modrinth.com/v2/project/Jw3Wx1KR/version?game_versions=[\"1.18\",\"1.18.2\"]&loaders=[\"fabric\",\"quilt\"]",
            url
        );
    }

    #[test]
    pub fn collect_conj() {
        let conj: FacetsConjunction = ["Technology", "Magic", "Adventure"]
            .iter()
            .map(|c| FacetsDisjunction::new_with(Facets::Categories(c.to_string())))
            .collect();

        let url = SearchBuilder::new()
            .facets(conj)
            .search_type(SearchType::Search { query: "".into(), limit: None, offset: None })
            .build_url();


        assert_eq!(
            "https://api.modrinth.com/v2/search?facets=[[\"categories:Technology\"],[\"categories:Magic\"],[\"categories:Adventure\"]]",
            url
        );
    }


    #[test]
    pub fn fold_disj() {
        let disj = ["Technology", "Magic", "Adventure"]
            .iter()
            .fold(FacetsDisjunction::new(), |acc,x| acc.or(Facets::Categories(x.to_string())));
            

        let url = SearchBuilder::new()
            .facets(FacetsConjunction::new_with(disj))
            .search_type(SearchType::Search { query: "".into(), limit: None, offset: None })
            .build_url();


        assert_eq!(
            "https://api.modrinth.com/v2/search?facets=[[\"categories:Technology\",\"categories:Magic\",\"categories:Adventure\"]]",
            url
        );
    }
}