tideway 0.7.17

A batteries-included Rust web framework built on Axum for building SaaS applications quickly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
//! Plan configuration and definitions.
//!
//! Define your subscription plans with features, seat limits, and pricing.
//!
//! # Static Plans (Code-configured)
//!
//! Use the builder pattern for plans defined in code:
//!
//! ```rust,ignore
//! use tideway::billing::{Plans, PlanLimits};
//!
//! let plans = Plans::builder()
//!     .plan("starter")
//!         .stripe_price("price_starter_monthly")
//!         .extra_seat_price("price_extra_seat")
//!         .included_seats(3)
//!         .features(["basic_reports", "email_support"])
//!         .trial_days(14)
//!         .done()?
//!     .plan("pro")
//!         .stripe_price("price_pro_monthly")
//!         .extra_seat_price("price_extra_seat")
//!         .included_seats(5)
//!         .features(["basic_reports", "advanced_reports", "api_access"])
//!         .done()?
//!     .build()?;
//! ```
//!
//! # Dynamic Plans (Database-backed)
//!
//! Use [`PlanStore`](super::storage::PlanStore) for admin-managed plans:
//!
//! ```rust,ignore
//! use tideway::billing::{Plans, PlanStore, StoredPlan};
//!
//! // Load plans from database
//! let stored_plans = store.list_plans().await?;
//! let plans = Plans::from_stored(stored_plans);
//! ```

use std::collections::{HashMap, HashSet};

use super::{error::BillingError, storage::StoredPlan};

/// A collection of plan configurations.
#[derive(Clone, Debug, Default)]
pub struct Plans {
    plans: HashMap<String, PlanConfig>,
}

impl Plans {
    /// Create a new empty plans collection.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a builder for constructing plans.
    #[must_use]
    pub fn builder() -> PlansBuilder {
        PlansBuilder::new()
    }

    /// Create a Plans collection from database-stored plans.
    ///
    /// This allows database-managed plans to be used with the existing
    /// code-configured plan system.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let stored_plans = store.list_plans().await?;
    /// let plans = Plans::from_stored(stored_plans);
    /// ```
    #[must_use]
    pub fn from_stored(stored: Vec<StoredPlan>) -> Self {
        let plans = stored
            .into_iter()
            .map(|sp| {
                let config = PlanConfig::from(sp);
                (config.id.clone(), config)
            })
            .collect();
        Self { plans }
    }

    /// Merge plans from another Plans collection.
    ///
    /// Returns an error if a plan ID from `other` already exists.
    pub fn merge(&mut self, other: Plans) -> Result<(), BillingError> {
        for (id, config) in other.plans {
            if self.plans.contains_key(&id) {
                return Err(BillingError::DuplicatePlanId { plan_id: id });
            }
            self.plans.insert(id, config);
        }
        Ok(())
    }

    /// Add a single plan config.
    ///
    /// Returns an error if a plan with the same ID already exists.
    pub fn add(&mut self, config: PlanConfig) -> Result<(), BillingError> {
        if self.plans.contains_key(&config.id) {
            return Err(BillingError::DuplicatePlanId {
                plan_id: config.id.clone(),
            });
        }
        self.plans.insert(config.id.clone(), config);
        Ok(())
    }

    /// Get a plan by ID.
    #[must_use]
    pub fn get(&self, plan_id: &str) -> Option<&PlanConfig> {
        self.plans.get(plan_id)
    }

    /// Get all plan IDs.
    #[must_use]
    pub fn plan_ids(&self) -> Vec<&str> {
        self.plans.keys().map(|s| s.as_str()).collect()
    }

    /// Check if a plan exists.
    #[must_use]
    pub fn contains(&self, plan_id: &str) -> bool {
        self.plans.contains_key(plan_id)
    }

    /// Get the number of plans.
    #[must_use]
    pub fn len(&self) -> usize {
        self.plans.len()
    }

    /// Check if there are no plans.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.plans.is_empty()
    }

    /// Iterate over all plans.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &PlanConfig)> {
        self.plans.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Find plan by Stripe price ID.
    #[must_use]
    pub fn find_by_stripe_price(&self, price_id: &str) -> Option<&PlanConfig> {
        self.plans.values().find(|p| p.stripe_price_id == price_id)
    }

    /// Get all Stripe price IDs (for validation).
    #[must_use]
    pub fn all_stripe_price_ids(&self) -> Vec<&str> {
        let mut ids: Vec<&str> = self
            .plans
            .values()
            .map(|p| p.stripe_price_id.as_str())
            .collect();

        // Also include extra seat prices
        for plan in self.plans.values() {
            if let Some(ref seat_price) = plan.extra_seat_price_id {
                ids.push(seat_price.as_str());
            }
        }

        ids
    }
}

/// Configuration for a single plan.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanConfig {
    /// Plan identifier (e.g., "starter", "pro").
    pub id: String,
    /// Stripe price ID for the base subscription.
    pub stripe_price_id: String,
    /// Stripe price ID for additional seats (optional).
    pub extra_seat_price_id: Option<String>,
    /// Number of seats included in the base price.
    pub included_seats: u32,
    /// Features available on this plan.
    pub features: HashSet<String>,
    /// Resource limits for this plan.
    pub limits: PlanLimits,
    /// Trial period in days (None = no trial).
    pub trial_days: Option<u32>,
    /// Display name for the plan.
    pub display_name: Option<String>,
    /// Description of the plan.
    pub description: Option<String>,
    /// Currency code (e.g., "gbp", "usd", "eur").
    /// This should match the currency of the Stripe price.
    /// Used for display purposes and validation.
    pub currency: Option<String>,
}

impl PlanConfig {
    /// Check if this plan has a specific feature.
    #[must_use]
    pub fn has_feature(&self, feature: &str) -> bool {
        self.features.contains(feature)
    }

    /// Check if this plan supports extra seats.
    #[must_use]
    pub fn supports_extra_seats(&self) -> bool {
        self.extra_seat_price_id.is_some()
    }

    /// Get the total seats for a given number of extra seats.
    #[must_use]
    pub fn total_seats(&self, extra_seats: u32) -> u32 {
        self.included_seats.saturating_add(extra_seats)
    }

    /// Check if a resource usage is within limits.
    #[must_use]
    pub fn check_limit(&self, resource: &str, current: u64) -> LimitCheckResult {
        self.limits.check(resource, current)
    }
}

impl From<StoredPlan> for PlanConfig {
    fn from(stored: StoredPlan) -> Self {
        // Convert features JSON to HashSet<String>
        let features = stored
            .features
            .as_object()
            .map(|obj| {
                obj.iter()
                    .filter_map(|(k, v)| {
                        if v.as_bool().unwrap_or(false) {
                            Some(k.clone())
                        } else {
                            None
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();

        // Convert limits JSON to PlanLimits
        let limits = PlanLimits::from_json(&stored.limits);

        Self {
            id: stored.id,
            stripe_price_id: stored.stripe_price_id,
            extra_seat_price_id: stored.stripe_seat_price_id,
            included_seats: stored.included_seats,
            features,
            limits,
            trial_days: stored.trial_days,
            display_name: Some(stored.name),
            description: stored.description,
            currency: Some(stored.currency),
        }
    }
}

/// Resource limits for a plan.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PlanLimits {
    /// Maximum number of projects.
    pub max_projects: Option<u32>,
    /// Maximum storage in megabytes.
    pub max_storage_mb: Option<u64>,
    /// Maximum API calls per month.
    pub max_api_calls_monthly: Option<u32>,
    /// Custom limits (extensible).
    pub custom: HashMap<String, u64>,
}

impl PlanLimits {
    /// Create unlimited limits.
    #[must_use]
    pub fn unlimited() -> Self {
        Self::default()
    }

    /// Create PlanLimits from a JSON value.
    ///
    /// Recognizes keys: "projects", "storage_mb", "api_calls", and any custom keys.
    #[must_use]
    pub fn from_json(json: &serde_json::Value) -> Self {
        let obj = match json.as_object() {
            Some(o) => o,
            None => return Self::default(),
        };

        let mut limits = Self::default();
        let mut custom = HashMap::new();

        for (key, value) in obj {
            let num = value.as_i64().or_else(|| value.as_u64().map(|n| n as i64));
            if let Some(n) = num {
                match key.as_str() {
                    "projects" | "max_projects" => limits.max_projects = Some(n as u32),
                    "storage_mb" | "max_storage_mb" => limits.max_storage_mb = Some(n as u64),
                    "api_calls" | "max_api_calls" | "max_api_calls_monthly" => {
                        limits.max_api_calls_monthly = Some(n as u32)
                    }
                    _ => {
                        custom.insert(key.clone(), n as u64);
                    }
                }
            }
        }

        limits.custom = custom;
        limits
    }

    /// Check if a resource usage is within limits.
    #[must_use]
    pub fn check(&self, resource: &str, current: u64) -> LimitCheckResult {
        let limit = match resource {
            "projects" => self.max_projects.map(|v| v as u64),
            "storage_mb" => self.max_storage_mb,
            "api_calls" => self.max_api_calls_monthly.map(|v| v as u64),
            _ => self.custom.get(resource).copied(),
        };

        match limit {
            None => LimitCheckResult::Unlimited,
            Some(max) if current < max => LimitCheckResult::WithinLimit { current, max },
            Some(max) => LimitCheckResult::AtLimit { current, max },
        }
    }

    /// Get a specific limit value.
    #[must_use]
    pub fn get(&self, resource: &str) -> Option<u64> {
        match resource {
            "projects" => self.max_projects.map(|v| v as u64),
            "storage_mb" => self.max_storage_mb,
            "api_calls" => self.max_api_calls_monthly.map(|v| v as u64),
            _ => self.custom.get(resource).copied(),
        }
    }
}

/// Result of checking a resource limit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LimitCheckResult {
    /// No limit on this resource.
    Unlimited,
    /// Usage is within the limit.
    WithinLimit { current: u64, max: u64 },
    /// Usage has reached or exceeded the limit.
    AtLimit { current: u64, max: u64 },
}

impl LimitCheckResult {
    /// Check if usage is allowed.
    #[must_use]
    pub fn is_allowed(&self) -> bool {
        matches!(self, Self::Unlimited | Self::WithinLimit { .. })
    }

    /// Check if at or over limit.
    #[must_use]
    pub fn is_at_limit(&self) -> bool {
        matches!(self, Self::AtLimit { .. })
    }
}

/// Builder for constructing a collection of plans.
#[derive(Debug, Default)]
pub struct PlansBuilder {
    plans: HashMap<String, PlanConfig>,
}

impl PlansBuilder {
    /// Create a new plans builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Start defining a new plan.
    #[must_use]
    pub fn plan(self, id: &str) -> PlanBuilder {
        PlanBuilder {
            parent: self,
            id: id.to_string(),
            stripe_price_id: None,
            extra_seat_price_id: None,
            included_seats: 1,
            features: HashSet::new(),
            limits: PlanLimits::default(),
            trial_days: None,
            display_name: None,
            description: None,
            currency: None,
        }
    }

    /// Build the plans collection.
    pub fn build(self) -> Result<Plans, BillingError> {
        Ok(Plans { plans: self.plans })
    }

    fn add_plan(mut self, config: PlanConfig) -> Result<Self, BillingError> {
        if self.plans.contains_key(&config.id) {
            return Err(BillingError::DuplicatePlanId { plan_id: config.id });
        }
        self.plans.insert(config.id.clone(), config);
        Ok(self)
    }
}

/// Builder for a single plan configuration.
#[derive(Debug)]
pub struct PlanBuilder {
    parent: PlansBuilder,
    id: String,
    stripe_price_id: Option<String>,
    extra_seat_price_id: Option<String>,
    included_seats: u32,
    features: HashSet<String>,
    limits: PlanLimits,
    trial_days: Option<u32>,
    display_name: Option<String>,
    description: Option<String>,
    currency: Option<String>,
}

impl PlanBuilder {
    /// Set the Stripe price ID for the base subscription.
    #[must_use]
    pub fn stripe_price(mut self, price_id: &str) -> Self {
        self.stripe_price_id = Some(price_id.to_string());
        self
    }

    /// Set the Stripe price ID for additional seats.
    #[must_use]
    pub fn extra_seat_price(mut self, price_id: &str) -> Self {
        self.extra_seat_price_id = Some(price_id.to_string());
        self
    }

    /// Set the number of seats included in the base price.
    #[must_use]
    pub fn included_seats(mut self, seats: u32) -> Self {
        self.included_seats = seats;
        self
    }

    /// Add features to this plan.
    #[must_use]
    pub fn features<I, S>(mut self, features: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.features.extend(features.into_iter().map(Into::into));
        self
    }

    /// Add a single feature to this plan.
    #[must_use]
    pub fn feature(mut self, feature: &str) -> Self {
        self.features.insert(feature.to_string());
        self
    }

    /// Set the maximum number of projects.
    #[must_use]
    pub fn max_projects(mut self, max: u32) -> Self {
        self.limits.max_projects = Some(max);
        self
    }

    /// Set the maximum storage in MB.
    #[must_use]
    pub fn max_storage_mb(mut self, max: u64) -> Self {
        self.limits.max_storage_mb = Some(max);
        self
    }

    /// Set the maximum API calls per month.
    #[must_use]
    pub fn max_api_calls(mut self, max: u32) -> Self {
        self.limits.max_api_calls_monthly = Some(max);
        self
    }

    /// Set a custom limit.
    #[must_use]
    pub fn custom_limit(mut self, name: &str, max: u64) -> Self {
        self.limits.custom.insert(name.to_string(), max);
        self
    }

    /// Set the full limits configuration.
    #[must_use]
    pub fn limits(mut self, limits: PlanLimits) -> Self {
        self.limits = limits;
        self
    }

    /// Set the trial period in days.
    #[must_use]
    pub fn trial_days(mut self, days: u32) -> Self {
        self.trial_days = Some(days);
        self
    }

    /// Set the display name.
    #[must_use]
    pub fn display_name(mut self, name: &str) -> Self {
        self.display_name = Some(name.to_string());
        self
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, desc: &str) -> Self {
        self.description = Some(desc.to_string());
        self
    }

    /// Set the currency code (e.g., "gbp", "usd", "eur").
    ///
    /// This should match the currency of your Stripe price.
    /// Used for display purposes and validation.
    #[must_use]
    pub fn currency(mut self, currency: &str) -> Self {
        self.currency = Some(currency.to_lowercase());
        self
    }

    /// Finish defining this plan and return to the parent builder.
    ///
    /// # Errors
    ///
    /// Returns an error if `stripe_price` was not set.
    pub fn done(self) -> Result<PlansBuilder, BillingError> {
        let id = self.id;
        let stripe_price_id = self
            .stripe_price_id
            .ok_or(BillingError::MissingStripePrice {
                plan_id: id.clone(),
            })?;

        let config = PlanConfig {
            id,
            stripe_price_id,
            extra_seat_price_id: self.extra_seat_price_id,
            included_seats: self.included_seats,
            features: self.features,
            limits: self.limits,
            trial_days: self.trial_days,
            display_name: self.display_name,
            description: self.description,
            currency: self.currency,
        };
        self.parent.add_plan(config)
    }
}

// =============================================================================
// Plan Upgrade/Downgrade Helpers
// =============================================================================

/// Result of comparing two plans.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlanChangeType {
    /// Moving to a plan with more features/seats/limits.
    Upgrade,
    /// Moving to a plan with fewer features/seats/limits.
    Downgrade,
    /// Plans are equivalent (same tier).
    Lateral,
    /// Plans are the same.
    NoChange,
}

impl std::fmt::Display for PlanChangeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Upgrade => write!(f, "upgrade"),
            Self::Downgrade => write!(f, "downgrade"),
            Self::Lateral => write!(f, "lateral"),
            Self::NoChange => write!(f, "no_change"),
        }
    }
}

/// Detailed comparison between two plans.
#[derive(Debug, Clone)]
pub struct PlanComparison {
    /// The type of change (upgrade, downgrade, etc.).
    pub change_type: PlanChangeType,
    /// Features gained by switching to the new plan.
    pub features_gained: HashSet<String>,
    /// Features lost by switching to the new plan.
    pub features_lost: HashSet<String>,
    /// Difference in included seats (positive = more seats).
    pub seat_difference: i32,
    /// Whether extra seats support changes.
    pub extra_seats_support_changed: bool,
    /// Warning messages (e.g., "Current extra seats exceed new plan's included seats").
    pub warnings: Vec<String>,
}

impl PlanComparison {
    /// Check if this change requires user confirmation.
    ///
    /// Returns true if features will be lost or warnings exist.
    #[must_use]
    pub fn requires_confirmation(&self) -> bool {
        !self.features_lost.is_empty() || !self.warnings.is_empty()
    }

    /// Check if this is a safe change (no features lost, no warnings).
    #[must_use]
    pub fn is_safe(&self) -> bool {
        self.features_lost.is_empty() && self.warnings.is_empty()
    }
}

/// Compare two plans to determine upgrade/downgrade status.
///
/// This function analyzes the differences between plans based on:
/// - Feature count
/// - Included seats
/// - Resource limits
///
/// # Arguments
///
/// * `from_plan` - The current plan
/// * `to_plan` - The target plan
///
/// # Example
///
/// ```rust,ignore
/// use tideway::billing::{compare_plans, PlanChangeType};
///
/// let comparison = compare_plans(current_plan, new_plan);
/// match comparison.change_type {
///     PlanChangeType::Upgrade => println!("Upgrading!"),
///     PlanChangeType::Downgrade => {
///         if !comparison.features_lost.is_empty() {
///             println!("Warning: You will lose: {:?}", comparison.features_lost);
///         }
///     }
///     _ => {}
/// }
/// ```
#[must_use]
pub fn compare_plans(from_plan: &PlanConfig, to_plan: &PlanConfig) -> PlanComparison {
    // Check for no change
    if from_plan.id == to_plan.id {
        return PlanComparison {
            change_type: PlanChangeType::NoChange,
            features_gained: HashSet::new(),
            features_lost: HashSet::new(),
            seat_difference: 0,
            extra_seats_support_changed: false,
            warnings: vec![],
        };
    }

    // Calculate feature differences
    let features_gained: HashSet<String> = to_plan
        .features
        .difference(&from_plan.features)
        .cloned()
        .collect();
    let features_lost: HashSet<String> = from_plan
        .features
        .difference(&to_plan.features)
        .cloned()
        .collect();

    // Calculate seat difference
    let seat_difference = to_plan.included_seats as i32 - from_plan.included_seats as i32;

    // Check extra seats support change
    let extra_seats_support_changed =
        from_plan.supports_extra_seats() != to_plan.supports_extra_seats();

    // Generate warnings
    let mut warnings = vec![];
    if extra_seats_support_changed && from_plan.supports_extra_seats() {
        warnings.push(
            "New plan does not support extra seats. Extra seats will be removed.".to_string(),
        );
    }
    if seat_difference < 0 {
        warnings.push(format!(
            "New plan has {} fewer included seats.",
            -seat_difference
        ));
    }

    // Determine change type based on heuristics
    let feature_score = features_gained.len() as i32 - features_lost.len() as i32;

    let change_type = if feature_score > 0 || seat_difference > 0 {
        PlanChangeType::Upgrade
    } else if feature_score < 0 || seat_difference < 0 || !features_lost.is_empty() {
        PlanChangeType::Downgrade
    } else {
        PlanChangeType::Lateral
    };

    PlanComparison {
        change_type,
        features_gained,
        features_lost,
        seat_difference,
        extra_seats_support_changed,
        warnings,
    }
}

/// Check if a plan can be downgraded given current usage.
///
/// # Arguments
///
/// * `from_plan` - The current plan
/// * `to_plan` - The target plan
/// * `current_extra_seats` - Number of extra seats currently in use
/// * `current_total_members` - Total members currently using the subscription
///
/// # Returns
///
/// Returns `Ok(())` if the downgrade is allowed, or `Err` with a reason if not.
///
/// # Example
///
/// ```rust,ignore
/// use tideway::billing::can_downgrade;
///
/// match can_downgrade(current_plan, new_plan, extra_seats, total_members) {
///     Ok(()) => println!("Downgrade allowed"),
///     Err(reason) => println!("Cannot downgrade: {}", reason),
/// }
/// ```
pub fn can_downgrade(
    _from_plan: &PlanConfig,
    to_plan: &PlanConfig,
    current_extra_seats: u32,
    current_total_members: u32,
) -> Result<(), PlanDowngradeError> {
    // Check if new plan has enough seats
    let new_total_seats = if to_plan.supports_extra_seats() {
        to_plan.included_seats + current_extra_seats
    } else {
        to_plan.included_seats
    };

    if current_total_members > new_total_seats {
        return Err(PlanDowngradeError::InsufficientSeats {
            current_members: current_total_members,
            new_seats: new_total_seats,
        });
    }

    // Check if extra seats are needed but not supported
    if current_extra_seats > 0 && !to_plan.supports_extra_seats() {
        let min_needed = current_total_members.saturating_sub(to_plan.included_seats);
        if min_needed > 0 {
            return Err(PlanDowngradeError::ExtraSeatsRequired {
                extra_needed: min_needed,
            });
        }
    }

    Ok(())
}

/// Error type for plan downgrade validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlanDowngradeError {
    /// Not enough seats on the new plan.
    InsufficientSeats {
        current_members: u32,
        new_seats: u32,
    },
    /// Extra seats are needed but the new plan doesn't support them.
    ExtraSeatsRequired { extra_needed: u32 },
}

impl std::fmt::Display for PlanDowngradeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InsufficientSeats {
                current_members,
                new_seats,
            } => {
                write!(
                    f,
                    "Cannot downgrade: you have {} members but the new plan only supports {} seats",
                    current_members, new_seats
                )
            }
            Self::ExtraSeatsRequired { extra_needed } => {
                write!(
                    f,
                    "Cannot downgrade: you need {} extra seats but the new plan doesn't support extra seats",
                    extra_needed
                )
            }
        }
    }
}

impl std::error::Error for PlanDowngradeError {}

/// Get a list of suggested plans for an upgrade.
///
/// Returns plans that have more features than the current plan,
/// sorted by feature count (most additional features first).
///
/// # Example
///
/// ```rust,ignore
/// let suggestions = plans.suggest_upgrades(current_plan);
/// for plan in suggestions {
///     println!("Consider upgrading to: {}", plan.id);
/// }
/// ```
impl Plans {
    /// Suggest upgrade options from the current plan.
    ///
    /// Returns plans that have strictly more features, sorted by the number
    /// of additional features (descending).
    #[must_use]
    pub fn suggest_upgrades(&self, current_plan: &PlanConfig) -> Vec<&PlanConfig> {
        let mut upgrades: Vec<(&PlanConfig, usize)> = self
            .plans
            .values()
            .filter(|p| {
                // Different plan
                p.id != current_plan.id
                    // Has more features
                    && p.features.is_superset(&current_plan.features)
                    && p.features.len() > current_plan.features.len()
            })
            .map(|p| {
                let additional = p.features.len() - current_plan.features.len();
                (p, additional)
            })
            .collect();

        // Sort by additional features (descending)
        upgrades.sort_by(|a, b| b.1.cmp(&a.1));

        upgrades.into_iter().map(|(p, _)| p).collect()
    }

    /// Find the next tier up from the current plan.
    ///
    /// Returns the upgrade with the fewest additional features (minimal upgrade).
    #[must_use]
    pub fn next_tier_up(&self, current_plan: &PlanConfig) -> Option<&PlanConfig> {
        self.plans
            .values()
            .filter(|p| {
                p.id != current_plan.id
                    && p.features.is_superset(&current_plan.features)
                    && p.features.len() > current_plan.features.len()
            })
            .min_by_key(|p| p.features.len())
    }
}

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

    #[test]
    fn test_build_plans() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .included_seats(3)
            .features(["reports", "email_support"])
            .trial_days(14)
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .extra_seat_price("price_seat")
            .included_seats(5)
            .features(["reports", "api_access", "priority_support"])
            .max_projects(100)
            .done()
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(plans.len(), 2);
        assert!(plans.contains("starter"));
        assert!(plans.contains("pro"));
    }

    #[test]
    fn test_plan_features() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .features(["reports"])
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .features(["reports", "api_access"])
            .done()
            .unwrap()
            .build()
            .unwrap();

        let starter = plans.get("starter").unwrap();
        assert!(starter.has_feature("reports"));
        assert!(!starter.has_feature("api_access"));

        let pro = plans.get("pro").unwrap();
        assert!(pro.has_feature("reports"));
        assert!(pro.has_feature("api_access"));
    }

    #[test]
    fn test_plan_seats() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .included_seats(3)
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .extra_seat_price("price_seat")
            .included_seats(5)
            .done()
            .unwrap()
            .build()
            .unwrap();

        let starter = plans.get("starter").unwrap();
        assert_eq!(starter.included_seats, 3);
        assert!(!starter.supports_extra_seats());
        assert_eq!(starter.total_seats(0), 3);

        let pro = plans.get("pro").unwrap();
        assert_eq!(pro.included_seats, 5);
        assert!(pro.supports_extra_seats());
        assert_eq!(pro.total_seats(3), 8);
    }

    #[test]
    fn test_plan_limits() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .max_projects(10)
            .max_storage_mb(1024)
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .max_projects(100)
            .custom_limit("widgets", 500)
            .done()
            .unwrap()
            .build()
            .unwrap();

        let starter = plans.get("starter").unwrap();
        assert!(starter.check_limit("projects", 5).is_allowed());
        assert!(starter.check_limit("projects", 10).is_at_limit());
        assert!(starter.check_limit("projects", 15).is_at_limit());

        let pro = plans.get("pro").unwrap();
        assert_eq!(
            pro.check_limit("widgets", 400),
            LimitCheckResult::WithinLimit {
                current: 400,
                max: 500
            }
        );
    }

    #[test]
    fn test_unlimited_limits() {
        let plans = Plans::builder()
            .plan("enterprise")
            .stripe_price("price_enterprise")
            .done()
            .unwrap()
            .build()
            .unwrap();

        let enterprise = plans.get("enterprise").unwrap();
        assert_eq!(
            enterprise.check_limit("projects", 10000),
            LimitCheckResult::Unlimited
        );
    }

    #[test]
    fn test_find_by_stripe_price() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_abc123")
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_xyz789")
            .done()
            .unwrap()
            .build()
            .unwrap();

        let found = plans.find_by_stripe_price("price_abc123");
        assert!(found.is_some());
        assert_eq!(found.unwrap().id, "starter");

        let not_found = plans.find_by_stripe_price("price_unknown");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_all_stripe_price_ids() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .extra_seat_price("price_seat")
            .done()
            .unwrap()
            .build()
            .unwrap();

        let ids = plans.all_stripe_price_ids();
        assert!(ids.contains(&"price_starter"));
        assert!(ids.contains(&"price_pro"));
        assert!(ids.contains(&"price_seat"));
    }

    #[test]
    fn test_trial_days() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .trial_days(14)
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .done()
            .unwrap()
            .build()
            .unwrap();

        let starter = plans.get("starter").unwrap();
        assert_eq!(starter.trial_days, Some(14));

        let pro = plans.get("pro").unwrap();
        assert_eq!(pro.trial_days, None);
    }

    #[test]
    fn test_compare_plans_upgrade() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .included_seats(3)
            .features(["reports"])
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .included_seats(5)
            .features(["reports", "api_access", "priority_support"])
            .done()
            .unwrap()
            .build()
            .unwrap();

        let starter = plans.get("starter").unwrap();
        let pro = plans.get("pro").unwrap();

        let comparison = compare_plans(starter, pro);
        assert_eq!(comparison.change_type, PlanChangeType::Upgrade);
        assert!(comparison.features_gained.contains("api_access"));
        assert!(comparison.features_gained.contains("priority_support"));
        assert!(comparison.features_lost.is_empty());
        assert_eq!(comparison.seat_difference, 2);
        assert!(comparison.is_safe());
    }

    #[test]
    fn test_compare_plans_downgrade() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .included_seats(3)
            .features(["reports"])
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .included_seats(5)
            .features(["reports", "api_access"])
            .done()
            .unwrap()
            .build()
            .unwrap();

        let starter = plans.get("starter").unwrap();
        let pro = plans.get("pro").unwrap();

        let comparison = compare_plans(pro, starter);
        assert_eq!(comparison.change_type, PlanChangeType::Downgrade);
        assert!(comparison.features_lost.contains("api_access"));
        assert!(comparison.features_gained.is_empty());
        assert_eq!(comparison.seat_difference, -2);
        assert!(comparison.requires_confirmation());
    }

    #[test]
    fn test_compare_plans_no_change() {
        let plans = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .features(["reports"])
            .done()
            .unwrap()
            .build()
            .unwrap();

        let starter = plans.get("starter").unwrap();

        let comparison = compare_plans(starter, starter);
        assert_eq!(comparison.change_type, PlanChangeType::NoChange);
    }

    #[test]
    fn test_compare_plans_lateral() {
        let plans = Plans::builder()
            .plan("monthly")
            .stripe_price("price_monthly")
            .included_seats(5)
            .features(["reports", "api_access"])
            .done()
            .unwrap()
            .plan("yearly")
            .stripe_price("price_yearly")
            .included_seats(5)
            .features(["reports", "api_access"])
            .done()
            .unwrap()
            .build()
            .unwrap();

        let monthly = plans.get("monthly").unwrap();
        let yearly = plans.get("yearly").unwrap();

        let comparison = compare_plans(monthly, yearly);
        assert_eq!(comparison.change_type, PlanChangeType::Lateral);
    }

    #[test]
    fn test_can_downgrade_allowed() {
        let plans = Plans::builder()
            .plan("pro")
            .stripe_price("price_pro")
            .extra_seat_price("price_seat")
            .included_seats(5)
            .done()
            .unwrap()
            .plan("starter")
            .stripe_price("price_starter")
            .included_seats(3)
            .done()
            .unwrap()
            .build()
            .unwrap();

        let pro = plans.get("pro").unwrap();
        let starter = plans.get("starter").unwrap();

        // 3 members, 0 extra seats - fits in starter's 3 included seats
        assert!(can_downgrade(pro, starter, 0, 3).is_ok());
    }

    #[test]
    fn test_can_downgrade_insufficient_seats() {
        let plans = Plans::builder()
            .plan("pro")
            .stripe_price("price_pro")
            .extra_seat_price("price_seat")
            .included_seats(10)
            .done()
            .unwrap()
            .plan("starter")
            .stripe_price("price_starter")
            .included_seats(3)
            .done()
            .unwrap()
            .build()
            .unwrap();

        let pro = plans.get("pro").unwrap();
        let starter = plans.get("starter").unwrap();

        // 8 members won't fit in starter's 3 seats
        let result = can_downgrade(pro, starter, 0, 8);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PlanDowngradeError::InsufficientSeats {
                current_members: 8,
                new_seats: 3
            }
        ));
    }

    #[test]
    fn test_can_downgrade_with_extra_seats_that_fit() {
        let plans = Plans::builder()
            .plan("pro")
            .stripe_price("price_pro")
            .extra_seat_price("price_seat")
            .included_seats(5)
            .done()
            .unwrap()
            .plan("basic")
            .stripe_price("price_basic")
            .included_seats(10) // More included seats, but no extra seats support
            .done()
            .unwrap()
            .build()
            .unwrap();

        let pro = plans.get("pro").unwrap();
        let basic = plans.get("basic").unwrap();

        // Currently on pro with 2 extra seats, 5 members
        // Downgrading to basic (10 included) - 5 members easily fits
        let result = can_downgrade(pro, basic, 2, 5);
        assert!(result.is_ok());

        // 10 members would also fit
        let result = can_downgrade(pro, basic, 5, 10);
        assert!(result.is_ok());

        // 11 members wouldn't fit
        let result = can_downgrade(pro, basic, 6, 11);
        assert!(result.is_err());
    }

    #[test]
    fn test_suggest_upgrades() {
        let plans = Plans::builder()
            .plan("free")
            .stripe_price("price_free")
            .features(["basic"])
            .done()
            .unwrap()
            .plan("starter")
            .stripe_price("price_starter")
            .features(["basic", "reports"])
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .features(["basic", "reports", "api_access"])
            .done()
            .unwrap()
            .plan("enterprise")
            .stripe_price("price_enterprise")
            .features(["basic", "reports", "api_access", "sso", "audit"])
            .done()
            .unwrap()
            .build()
            .unwrap();

        let free = plans.get("free").unwrap();
        let suggestions = plans.suggest_upgrades(free);

        // All plans are supersets of free, sorted by feature count desc
        assert_eq!(suggestions.len(), 3);
        assert_eq!(suggestions[0].id, "enterprise"); // Most features
        assert_eq!(suggestions[1].id, "pro");
        assert_eq!(suggestions[2].id, "starter"); // Fewest additional features
    }

    #[test]
    fn test_next_tier_up() {
        let plans = Plans::builder()
            .plan("free")
            .stripe_price("price_free")
            .features(["basic"])
            .done()
            .unwrap()
            .plan("starter")
            .stripe_price("price_starter")
            .features(["basic", "reports"])
            .done()
            .unwrap()
            .plan("pro")
            .stripe_price("price_pro")
            .features(["basic", "reports", "api_access"])
            .done()
            .unwrap()
            .build()
            .unwrap();

        let free = plans.get("free").unwrap();
        let next = plans.next_tier_up(free);

        assert!(next.is_some());
        assert_eq!(next.unwrap().id, "starter"); // Minimal upgrade
    }

    #[test]
    fn test_done_without_stripe_price_returns_error() {
        let result = Plans::builder().plan("starter").done();
        assert!(matches!(
            result,
            Err(BillingError::MissingStripePrice { plan_id }) if plan_id == "starter"
        ));
    }

    #[test]
    fn test_duplicate_plan_id_returns_error() {
        let result = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .done()
            .unwrap()
            .plan("starter")
            .stripe_price("price_starter_v2")
            .done();
        assert!(matches!(
            result,
            Err(BillingError::DuplicatePlanId { plan_id }) if plan_id == "starter"
        ));
    }

    #[test]
    fn test_add_duplicate_plan_id_returns_error() {
        let mut plans = Plans::new();
        let plan = PlanConfig {
            id: "starter".to_string(),
            stripe_price_id: "price_starter".to_string(),
            extra_seat_price_id: None,
            included_seats: 1,
            features: HashSet::new(),
            limits: PlanLimits::default(),
            trial_days: None,
            display_name: None,
            description: None,
            currency: None,
        };

        plans.add(plan.clone()).unwrap();
        let result = plans.add(plan);
        assert!(matches!(
            result,
            Err(BillingError::DuplicatePlanId { plan_id }) if plan_id == "starter"
        ));
    }

    #[test]
    fn test_merge_duplicate_plan_id_returns_error() {
        let mut existing = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter")
            .done()
            .unwrap()
            .build()
            .unwrap();
        let incoming = Plans::builder()
            .plan("starter")
            .stripe_price("price_starter_new")
            .done()
            .unwrap()
            .build()
            .unwrap();

        let result = existing.merge(incoming);
        assert!(matches!(
            result,
            Err(BillingError::DuplicatePlanId { plan_id }) if plan_id == "starter"
        ));
    }

    #[test]
    fn test_plan_change_type_display() {
        assert_eq!(PlanChangeType::Upgrade.to_string(), "upgrade");
        assert_eq!(PlanChangeType::Downgrade.to_string(), "downgrade");
        assert_eq!(PlanChangeType::Lateral.to_string(), "lateral");
        assert_eq!(PlanChangeType::NoChange.to_string(), "no_change");
    }

    #[test]
    fn test_plan_downgrade_error_display() {
        let err = PlanDowngradeError::InsufficientSeats {
            current_members: 10,
            new_seats: 3,
        };
        assert!(err.to_string().contains("10 members"));
        assert!(err.to_string().contains("3 seats"));

        let err = PlanDowngradeError::ExtraSeatsRequired { extra_needed: 5 };
        assert!(err.to_string().contains("5 extra seats"));
    }
}