what-core 1.7.0

Core framework for What - an HTML-first web framework powered by Rust
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
//! Configuration handling for What projects
//!
//! Parses what.toml files (legacy name wwwhat.toml still supported) that
//! define server settings, data sources, and caching.

use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::Result;

/// Main configuration structure parsed from what.toml
#[derive(Debug, Deserialize, Default, Clone)]
pub struct Config {
    /// Server configuration
    #[serde(default)]
    pub server: ServerConfig,

    /// Central data store definitions
    #[serde(default)]
    pub data: HashMap<String, DataSource>,

    /// Cache configuration
    #[serde(default)]
    pub cache: CacheConfig,

    /// Session configuration
    #[serde(default)]
    pub session: SessionConfig,

    /// Authentication configuration
    #[serde(default)]
    pub auth: AuthConfig,

    /// Upload configuration
    #[serde(default)]
    pub uploads: UploadConfig,

    /// Database configuration (when absent, auto-defaults to SQLite)
    #[serde(default)]
    pub database: Option<DatabaseConfig>,

    /// Rate limiting configuration
    #[serde(default)]
    pub rate_limit: RateLimitConfig,

    /// Email configuration
    #[serde(default)]
    pub email: Option<EmailConfig>,

    /// Global redirect rules: old path → new path
    /// Supports exact matches and wildcard prefixes ("/old/*" → "/new")
    #[serde(default)]
    pub redirects: HashMap<String, String>,

    /// Strict mode: warn about unresolved template variables
    #[serde(default)]
    pub strict: bool,

    /// Cloudflare configuration (shared credentials for D1, R2, Turnstile)
    #[serde(default)]
    pub cloudflare: Option<CloudflareConfig>,

    /// Supabase configuration
    #[serde(default)]
    pub supabase: Option<SupabaseConfig>,

    /// Named datasources — multiple backends accessible via `dsn:name` in fetch directives
    #[serde(default)]
    pub datasources: HashMap<String, DatasourceConfig>,

    /// Collection authorization policies — one entry per `[collections.<name>]`.
    /// Collections without an entry get the implicit owner-protected default:
    /// create = "all", update/delete = "owner", read = "all", owner = "auto".
    #[serde(default)]
    pub collections: HashMap<String, CollectionPolicyConfig>,
}

/// Raw per-collection authorization policy — one per `[collections.name]` in what.toml.
/// Semantic validation (reserved words, invalid combinations) happens when the
/// PolicyRegistry is built at startup, so errors fail loud with the collection name.
///
/// # Example (what.toml)
/// ```toml
/// [collections.notes]
/// create = "all"
/// update = "owner"
/// delete = "owner, admin"
/// read   = "owner"
///
/// [collections.orders]
/// filter = "org_id=#user.org_id#"
/// fields.private = ["internal_margin"]
/// ```
#[derive(Debug, Deserialize, Clone, Default)]
pub struct CollectionPolicyConfig {
    /// Ownership mode: "auto" (default — stamp _owner on create) or "none"
    pub owner: Option<String>,

    /// Who may create records: "all" | "user" | "none" | role list ("editor, admin")
    pub create: Option<String>,

    /// Who may update records: adds "owner" to the create vocabulary
    pub update: Option<String>,

    /// Who may delete records
    pub delete: Option<String>,

    /// Who may read records — owner/user/roles force a WHERE scope on every fetch
    pub read: Option<String>,

    /// Forced filter AND-ed into every read and checked on mutations.
    /// Supports `#user.*#` / `#session.*#` interpolation, e.g. "org_id=#user.org_id#"
    pub filter: Option<String>,

    /// Field-level rules
    #[serde(default)]
    pub fields: FieldRulesConfig,
}

/// Field-level policy rules for a collection
#[derive(Debug, Deserialize, Clone, Default)]
pub struct FieldRulesConfig {
    /// Fields stripped from client create/update input (server-managed values)
    #[serde(default)]
    pub readonly: Vec<String>,

    /// Fields stripped from records before they reach template context
    #[serde(default)]
    pub private: Vec<String>,
}

/// Named datasource configuration — one entry per `[datasources.name]` in what.toml
///
/// Supports multiple backend types:
/// - `"api"` — REST API with base URL and optional headers
/// - `"d1"` — Cloudflare D1 database
/// - `"supabase"` — Supabase (PostgREST)
/// - `"sqlite"` — Local SQLite database
///
/// # Example (what.toml)
/// ```toml
/// [datasources.users]
/// type = "supabase"
/// project_url = "${SUPABASE_URL}"
/// api_key = "${SUPABASE_KEY}"
///
/// [datasources.inventory]
/// type = "api"
/// url = "https://inventory.example.com"
/// headers = { Authorization = "Bearer ${API_TOKEN}" }
/// ```
/// Backend type for a named datasource
#[derive(Debug, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DatasourceType {
    Api,
    D1,
    Supabase,
    Sqlite,
}

#[derive(Debug, Deserialize, Clone)]
pub struct DatasourceConfig {
    /// Backend type
    pub r#type: DatasourceType,

    /// Base URL for API datasources
    pub url: Option<String>,

    /// HTTP headers for API datasources (key-value pairs, supports `${ENV_VAR}`)
    #[serde(default)]
    pub headers: Option<HashMap<String, String>>,

    /// Cloudflare account ID (D1 datasources)
    pub account_id: Option<String>,

    /// Cloudflare API token (D1 datasources)
    pub api_token: Option<String>,

    /// D1 database ID (D1 datasources)
    pub d1_database_id: Option<String>,

    /// Supabase project URL (Supabase datasources)
    pub project_url: Option<String>,

    /// Supabase API key (Supabase datasources)
    pub api_key: Option<String>,

    /// Path to SQLite database file (SQLite datasources)
    pub path: Option<String>,
}

/// Unified Cloudflare configuration — credentials shared across D1, R2, Turnstile
#[derive(Debug, Deserialize, Clone)]
pub struct CloudflareConfig {
    /// Cloudflare account ID
    pub account_id: String,

    /// API token (default for all services, overridable per-service)
    pub api_token: String,

    /// D1 database ID (enables `type = "d1"` in [database])
    pub d1_database_id: Option<String>,

    /// R2 bucket name (enables `provider = "r2"` in [uploads])
    pub r2_bucket: Option<String>,

    /// R2 public URL prefix (e.g., "https://pub-xxx.r2.dev")
    pub r2_public_url: Option<String>,

    /// Turnstile site key (public, used in <what-turnstile> component)
    pub turnstile_site_key: Option<String>,

    /// Turnstile secret key (server-side verification)
    pub turnstile_secret_key: Option<String>,
}

/// Supabase configuration
#[derive(Debug, Deserialize, Clone)]
pub struct SupabaseConfig {
    /// Supabase project URL (e.g., "https://xxx.supabase.co")
    pub project_url: String,

    /// Supabase service_role key (NOT the anon key — bypasses Row Level Security)
    pub api_key: String,
}

/// Database configuration
#[derive(Debug, Deserialize, Clone)]
pub struct DatabaseConfig {
    /// Database type: "sqlite", "d1", or "supabase"
    #[serde(default = "default_db_type")]
    pub r#type: String,

    /// Path to the database file (relative to project root, SQLite only)
    #[serde(default = "default_db_path")]
    pub path: String,
}

fn default_db_type() -> String {
    "sqlite".to_string()
}

fn default_db_path() -> String {
    "data/app.db".to_string()
}

/// Server configuration
#[derive(Debug, Deserialize, Clone)]
pub struct ServerConfig {
    /// Port to listen on
    #[serde(default = "default_port")]
    pub port: u16,

    /// Host to bind to
    #[serde(default = "default_host")]
    pub host: String,

    /// Maximum request body size (e.g., "10mb", "500kb", "1gb")
    #[serde(default = "default_max_body_size")]
    pub max_body_size: String,

    /// Timeout for external fetch requests in seconds
    #[serde(default = "default_fetch_timeout")]
    pub fetch_timeout: u64,

    /// Enable the source viewer endpoint in production mode
    #[serde(default)]
    pub source_viewer: bool,

    /// Framework stylesheet mode: "full" (default — the whole design system),
    /// "minimal" (reset, theme variables, and utilities only — no component styles),
    /// or "none" (what.css is not auto-injected; bring your own CSS).
    #[serde(default = "default_css_mode")]
    pub css: String,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            port: default_port(),
            host: default_host(),
            max_body_size: default_max_body_size(),
            fetch_timeout: default_fetch_timeout(),
            source_viewer: false,
            css: default_css_mode(),
        }
    }
}

fn default_css_mode() -> String {
    "full".to_string()
}

fn default_fetch_timeout() -> u64 {
    10
}

fn default_max_body_size() -> String {
    "10mb".to_string()
}

fn default_port() -> u16 {
    8085
}

fn default_host() -> String {
    "127.0.0.1".to_string()
}

/// Data source definition for the central data store
#[derive(Debug, Deserialize, Clone)]
#[serde(untagged)]
pub enum DataSource {
    /// URL-based data source (external API)
    Url {
        url: String,
        #[serde(default = "default_cache_ttl")]
        cache: u64,
    },
    /// File-based data source (local JSON file)
    File {
        file: String,
        #[serde(default = "default_cache_ttl")]
        cache: u64,
    },
    /// Simple string path (shorthand for file)
    SimplePath(String),
}

fn default_cache_ttl() -> u64 {
    300 // 5 minutes
}

/// Cache configuration
#[derive(Debug, Deserialize, Clone)]
pub struct CacheConfig {
    /// Whether caching is enabled
    #[serde(default = "default_cache_enabled")]
    pub enabled: bool,

    /// Default TTL in seconds
    #[serde(default = "default_cache_ttl")]
    pub ttl: u64,

    /// Redis URL (optional, uses memory cache if not set)
    pub redis_url: Option<String>,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            enabled: default_cache_enabled(),
            ttl: default_cache_ttl(),
            redis_url: None,
        }
    }
}

fn default_cache_enabled() -> bool {
    true
}

/// Session configuration
#[derive(Debug, Deserialize, Clone)]
pub struct SessionConfig {
    /// Whether sessions are enabled
    #[serde(default = "default_session_enabled")]
    pub enabled: bool,

    /// Storage backend: "sqlite" (default) or "cloudflare-kv"
    #[serde(default = "default_session_store")]
    pub store: String,

    /// Cookie name for the session ID
    #[serde(default = "default_cookie_name")]
    pub cookie_name: String,

    /// Session max age in seconds (default: 7 days)
    #[serde(default = "default_session_max_age")]
    pub max_age: i64,

    /// Whether to use Secure flag on cookie (defaults to true for production safety)
    #[serde(default = "default_session_secure")]
    pub secure: bool,

    /// SQLite database file for sessions (used when store = "sqlite")
    #[serde(default = "default_session_database")]
    pub database: String,

    /// Cloudflare KV configuration (used when store = "cloudflare-kv")
    #[serde(default)]
    pub cloudflare: Option<CloudflareKvConfig>,
}

/// Cloudflare Workers KV configuration
#[derive(Debug, Deserialize, Clone)]
pub struct CloudflareKvConfig {
    /// Cloudflare account ID
    pub account_id: String,
    /// KV namespace ID
    pub namespace_id: String,
    /// API token with KV read/write permissions
    pub api_token: String,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            enabled: default_session_enabled(),
            store: default_session_store(),
            cookie_name: default_cookie_name(),
            max_age: default_session_max_age(),
            secure: default_session_secure(),
            database: default_session_database(),
            cloudflare: None,
        }
    }
}

fn default_session_enabled() -> bool {
    true
}

fn default_session_store() -> String {
    "sqlite".to_string()
}

fn default_cookie_name() -> String {
    "w_session".to_string()
}

fn default_session_max_age() -> i64 {
    604800 // 7 days in seconds
}

fn default_session_secure() -> bool {
    true
}

fn default_session_database() -> String {
    "sessions.db".to_string()
}

/// Authentication configuration
#[derive(Debug, Deserialize, Clone)]
pub struct AuthConfig {
    /// Whether authentication is enabled
    #[serde(default)]
    pub enabled: bool,

    /// Backend API URL for authentication (e.g., "https://api.example.com/auth/login")
    pub login_endpoint: Option<String>,

    /// Backend API URL for logout (optional)
    pub logout_endpoint: Option<String>,

    /// Cookie name for the JWT token
    #[serde(default = "default_jwt_cookie_name")]
    pub jwt_cookie_name: String,

    /// Path to redirect to after login
    #[serde(default = "default_after_login")]
    pub after_login: String,

    /// Path to the login page
    #[serde(default = "default_login_path")]
    pub login_path: String,

    /// Paths that require authentication (glob patterns)
    #[serde(default)]
    pub protected_paths: Vec<String>,

    /// JWT secret for validation (optional - if not set, JWT is decoded but not verified)
    pub jwt_secret: Option<String>,

    /// JWT claims to extract and make available in templates
    #[serde(default = "default_jwt_claims")]
    pub jwt_claims: Vec<String>,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            login_endpoint: None,
            logout_endpoint: None,
            jwt_cookie_name: default_jwt_cookie_name(),
            after_login: default_after_login(),
            login_path: default_login_path(),
            protected_paths: vec![],
            jwt_secret: None,
            jwt_claims: default_jwt_claims(),
        }
    }
}

fn default_jwt_cookie_name() -> String {
    "w_token".to_string()
}

fn default_after_login() -> String {
    "/".to_string()
}

fn default_login_path() -> String {
    "/login".to_string()
}

fn default_jwt_claims() -> Vec<String> {
    vec![
        "id".to_string(),
        "user_id".to_string(),
        "email".to_string(),
        "full_name".to_string(),
    ]
}

/// Upload configuration
#[derive(Debug, Deserialize, Clone)]
pub struct UploadConfig {
    /// Whether file uploads are enabled
    #[serde(default)]
    pub enabled: bool,

    /// Storage provider: "local" (default) or "r2"
    #[serde(default = "default_upload_provider")]
    pub provider: String,

    /// Directory for uploaded files (relative to project root, local only)
    #[serde(default = "default_upload_directory")]
    pub directory: String,

    /// Maximum file size (e.g., "10mb", "500kb", "1gb")
    #[serde(default = "default_upload_max_size")]
    pub max_size: String,

    /// Allowed MIME types (supports wildcards like "image/*")
    #[serde(default)]
    pub allowed_types: Vec<String>,
}

impl Default for UploadConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: default_upload_provider(),
            directory: default_upload_directory(),
            max_size: default_upload_max_size(),
            allowed_types: vec![],
        }
    }
}

fn default_upload_provider() -> String {
    "local".to_string()
}

fn default_upload_directory() -> String {
    "uploads".to_string()
}

fn default_upload_max_size() -> String {
    "10mb".to_string()
}

impl UploadConfig {
    /// Parse the max_size string ("10mb", "500kb", "1gb") into bytes
    pub fn max_size_bytes(&self) -> usize {
        parse_size_string(&self.max_size)
    }

    /// Check if a MIME type is allowed by the configuration
    pub fn is_type_allowed(&self, content_type: &str) -> bool {
        if self.allowed_types.is_empty() {
            return true; // No restrictions = allow all
        }
        for allowed in &self.allowed_types {
            if allowed == content_type {
                return true;
            }
            // Wildcard match: "image/*" matches "image/png"
            if allowed.ends_with("/*") {
                let prefix = &allowed[..allowed.len() - 1];
                if content_type.starts_with(prefix) {
                    return true;
                }
            }
            // Extension match: ".pdf" matches common MIME types
            if allowed.starts_with('.') {
                if mime_matches_extension(content_type, allowed) {
                    return true;
                }
            }
        }
        false
    }
}

/// Parse human-readable size strings into bytes
pub fn parse_size_string(s: &str) -> usize {
    let s = s.trim().to_lowercase();
    if let Some(num) = s.strip_suffix("gb") {
        num.trim().parse::<usize>().unwrap_or(0) * 1024 * 1024 * 1024
    } else if let Some(num) = s.strip_suffix("mb") {
        num.trim().parse::<usize>().unwrap_or(0) * 1024 * 1024
    } else if let Some(num) = s.strip_suffix("kb") {
        num.trim().parse::<usize>().unwrap_or(0) * 1024
    } else {
        s.parse::<usize>().unwrap_or(10 * 1024 * 1024) // default 10MB
    }
}

fn mime_matches_extension(content_type: &str, extension: &str) -> bool {
    match extension {
        ".pdf" => content_type == "application/pdf",
        ".doc" => content_type == "application/msword",
        ".docx" => {
            content_type
                == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        }
        ".xls" => content_type == "application/vnd.ms-excel",
        ".xlsx" => {
            content_type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        }
        ".csv" => content_type == "text/csv",
        ".txt" => content_type == "text/plain",
        ".zip" => content_type == "application/zip",
        _ => false,
    }
}

/// Rate limiting configuration
#[derive(Debug, Deserialize, Clone)]
pub struct RateLimitConfig {
    /// Whether rate limiting is enabled
    #[serde(default = "default_rate_limit_enabled")]
    pub enabled: bool,

    /// Login endpoint limit: "requests/seconds" (e.g., "5/60" = 5 per 60s)
    #[serde(default = "default_rate_limit_login")]
    pub login: String,

    /// Upload endpoint limit: "requests/seconds"
    #[serde(default = "default_rate_limit_upload")]
    pub upload: String,

    /// Action endpoint limit: "requests/seconds"
    #[serde(default = "default_rate_limit_action")]
    pub action: String,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            enabled: default_rate_limit_enabled(),
            login: default_rate_limit_login(),
            upload: default_rate_limit_upload(),
            action: default_rate_limit_action(),
        }
    }
}

fn default_rate_limit_enabled() -> bool {
    true
}

fn default_rate_limit_login() -> String {
    "5/60".to_string()
}

fn default_rate_limit_upload() -> String {
    "10/60".to_string()
}

fn default_rate_limit_action() -> String {
    "30/60".to_string()
}

impl RateLimitConfig {
    /// Parse a rate limit string like "5/60" into (max_requests, window_seconds)
    pub fn parse_limit(s: &str) -> (u32, u64) {
        let parts: Vec<&str> = s.split('/').collect();
        if parts.len() == 2 {
            let max = parts[0].trim().parse().unwrap_or(5);
            let window = parts[1].trim().parse().unwrap_or(60);
            (max, window)
        } else {
            (5, 60)
        }
    }
}

/// Email configuration
#[derive(Debug, Deserialize, Clone)]
pub struct EmailConfig {
    /// Sender email address
    pub from: String,

    /// Sender display name (optional)
    #[serde(default)]
    pub from_name: Option<String>,

    /// SMTP transport settings (mutually exclusive with `api`)
    pub smtp: Option<SmtpConfig>,

    /// API transport settings — e.g. Resend (mutually exclusive with `smtp`)
    pub api: Option<EmailApiConfig>,

    /// Template directory relative to project root (default: "emails")
    #[serde(default = "default_email_template_dir")]
    pub template_dir: String,
}

/// SMTP transport configuration
#[derive(Debug, Deserialize, Clone)]
pub struct SmtpConfig {
    /// SMTP host
    pub host: String,

    /// SMTP port (default: 587)
    #[serde(default = "default_smtp_port")]
    pub port: u16,

    /// SMTP username (supports `${ENV_VAR}` syntax)
    pub username: Option<String>,

    /// SMTP password (supports `${ENV_VAR}` syntax)
    pub password: Option<String>,
}

/// API-based email provider configuration (e.g. Resend)
#[derive(Debug, Deserialize, Clone)]
pub struct EmailApiConfig {
    /// Provider name: "resend"
    pub provider: String,

    /// API key (supports `${ENV_VAR}` syntax)
    pub api_key: String,
}

fn default_email_template_dir() -> String {
    "emails".to_string()
}

fn default_smtp_port() -> u16 {
    587
}

/// Resolve the config file path for a project directory.
///
/// Prefers `what.toml`; falls back to the legacy `wwwhat.toml` name (still
/// fully supported). When neither exists, returns the canonical `what.toml`
/// path so callers report the current name in messages.
pub fn resolve_config_path(project_dir: &Path) -> PathBuf {
    let canonical = project_dir.join("what.toml");
    if canonical.exists() {
        return canonical;
    }
    let legacy = project_dir.join("wwwhat.toml");
    if legacy.exists() {
        return legacy;
    }
    canonical
}

impl Config {
    /// Load configuration from a what.toml file.
    /// Unknown keys are warned about instead of silently dropped — a typo
    /// like `prt = 3000` otherwise falls back to the default port with no
    /// symptom at all — but never fail the load (forward compatibility).
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let file_name = path
            .as_ref()
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "what.toml".to_string());
        let content = std::fs::read_to_string(path)?;
        let de = toml::de::Deserializer::new(&content);
        let mut unknown_keys: Vec<String> = Vec::new();
        let config: Config = serde_ignored::deserialize(de, |ignored_path| {
            unknown_keys.push(ignored_path.to_string());
        })?;
        for key in unknown_keys {
            tracing::warn!(
                "{}: unknown key '{}' is ignored — possible typo? The default value applies.",
                file_name,
                key
            );
        }
        Ok(config)
    }

    /// Load configuration from the current directory
    pub fn load_from_current_dir() -> Result<Self> {
        let path = resolve_config_path(&std::env::current_dir()?);
        if path.exists() {
            Self::load(path)
        } else {
            Ok(Config::default())
        }
    }
}

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

    #[test]
    fn test_load_tolerates_unknown_keys() {
        // Unknown keys warn (typo detection) but must never fail the load
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("what.toml");
        std::fs::write(&path, "[server]\nprt = 3000\nport = 9090\n\n[nonsense]\nfoo = 1\n")
            .unwrap();
        let config = Config::load(&path).unwrap();
        assert_eq!(config.server.port, 9090);
    }

    // --- Default value tests ---

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert_eq!(config.server.port, 8085);
        assert_eq!(config.server.host, "127.0.0.1");
        assert!(config.data.is_empty());
        assert!(config.cache.enabled);
        assert_eq!(config.cache.ttl, 300);
        assert!(config.cache.redis_url.is_none());
        assert!(config.session.enabled);
        assert_eq!(config.session.cookie_name, "w_session");
        assert_eq!(config.session.max_age, 604800);
        assert!(config.session.secure);
        assert_eq!(config.session.database, "sessions.db");
        assert!(!config.auth.enabled);
        assert!(config.auth.login_endpoint.is_none());
        assert!(config.auth.logout_endpoint.is_none());
        assert_eq!(config.auth.jwt_cookie_name, "w_token");
        assert_eq!(config.auth.after_login, "/");
        assert_eq!(config.auth.login_path, "/login");
        assert!(config.auth.protected_paths.is_empty());
        assert!(config.auth.jwt_secret.is_none());
        assert_eq!(
            config.auth.jwt_claims,
            vec!["id", "user_id", "email", "full_name"]
        );
    }

    #[test]
    fn test_server_config_default() {
        let server = ServerConfig::default();
        assert_eq!(server.port, 8085);
        assert_eq!(server.host, "127.0.0.1");
    }

    #[test]
    fn test_cache_config_default() {
        let cache = CacheConfig::default();
        assert!(cache.enabled);
        assert_eq!(cache.ttl, 300);
        assert!(cache.redis_url.is_none());
    }

    #[test]
    fn test_session_config_default() {
        let session = SessionConfig::default();
        assert!(session.enabled);
        assert_eq!(session.store, "sqlite");
        assert_eq!(session.cookie_name, "w_session");
        assert_eq!(session.max_age, 604800); // 7 days
        assert!(session.secure); // Secure=true by default for production safety
        assert_eq!(session.database, "sessions.db");
        assert!(session.cloudflare.is_none());
    }

    #[test]
    fn test_auth_config_default() {
        let auth = AuthConfig::default();
        assert!(!auth.enabled);
        assert!(auth.login_endpoint.is_none());
        assert!(auth.logout_endpoint.is_none());
        assert_eq!(auth.jwt_cookie_name, "w_token");
        assert_eq!(auth.after_login, "/");
        assert_eq!(auth.login_path, "/login");
        assert!(auth.protected_paths.is_empty());
        assert!(auth.jwt_secret.is_none());
    }

    // --- TOML parsing tests ---

    #[test]
    fn test_parse_empty_toml() {
        let config: Config = toml::from_str("").unwrap();
        // All sections should fall back to defaults
        assert_eq!(config.server.port, 8085);
        assert_eq!(config.server.host, "127.0.0.1");
        assert!(config.data.is_empty());
        assert!(config.cache.enabled);
    }

    #[test]
    fn test_parse_full_config() {
        let toml_str = r#"
[server]
port = 3000
host = "0.0.0.0"

[data.products]
url = "https://api.example.com/products"
cache = 600

[data.posts]
file = "data/posts.json"
cache = 120

[data]
simple = "data/items.json"

[cache]
enabled = false
ttl = 60
redis_url = "redis://localhost:6379"

[session]
enabled = false
cookie_name = "my_session"
max_age = 3600
secure = true
database = "my_sessions.db"

[auth]
enabled = true
login_endpoint = "https://api.example.com/auth/login"
logout_endpoint = "https://api.example.com/auth/logout"
jwt_cookie_name = "my_token"
after_login = "/dashboard"
login_path = "/signin"
protected_paths = ["/admin/*", "/dashboard/*"]
jwt_secret = "supersecret"
jwt_claims = ["id", "email", "role"]
"#;
        let config: Config = toml::from_str(toml_str).unwrap();

        assert_eq!(config.server.port, 3000);
        assert_eq!(config.server.host, "0.0.0.0");

        assert!(!config.cache.enabled);
        assert_eq!(config.cache.ttl, 60);
        assert_eq!(
            config.cache.redis_url.as_deref(),
            Some("redis://localhost:6379")
        );

        assert!(!config.session.enabled);
        assert_eq!(config.session.cookie_name, "my_session");
        assert_eq!(config.session.max_age, 3600);
        assert!(config.session.secure);
        assert_eq!(config.session.database, "my_sessions.db");

        assert!(config.auth.enabled);
        assert_eq!(
            config.auth.login_endpoint.as_deref(),
            Some("https://api.example.com/auth/login")
        );
        assert_eq!(
            config.auth.logout_endpoint.as_deref(),
            Some("https://api.example.com/auth/logout")
        );
        assert_eq!(config.auth.jwt_cookie_name, "my_token");
        assert_eq!(config.auth.after_login, "/dashboard");
        assert_eq!(config.auth.login_path, "/signin");
        assert_eq!(
            config.auth.protected_paths,
            vec!["/admin/*", "/dashboard/*"]
        );
        assert_eq!(config.auth.jwt_secret.as_deref(), Some("supersecret"));
        assert_eq!(config.auth.jwt_claims, vec!["id", "email", "role"]);
    }

    #[test]
    fn test_parse_partial_config_only_server() {
        let toml_str = r#"
[server]
port = 9090
"#;
        let config: Config = toml::from_str(toml_str).unwrap();

        assert_eq!(config.server.port, 9090);
        assert_eq!(config.server.host, "127.0.0.1"); // default
        assert!(config.data.is_empty()); // default
        assert!(config.cache.enabled); // default
        assert!(config.session.enabled); // default
        assert!(!config.auth.enabled); // default
    }

    #[test]
    fn test_parse_partial_config_only_auth() {
        let toml_str = r#"
[auth]
enabled = true
login_endpoint = "https://api.example.com/login"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();

        assert!(config.auth.enabled);
        assert_eq!(
            config.auth.login_endpoint.as_deref(),
            Some("https://api.example.com/login")
        );
        // Other auth fields should be defaults
        assert_eq!(config.auth.jwt_cookie_name, "w_token");
        assert_eq!(config.auth.after_login, "/");
        assert_eq!(config.auth.login_path, "/login");
        // Other sections should be defaults
        assert_eq!(config.server.port, 8085);
    }

    #[test]
    fn test_session_secure_defaults_true() {
        // No [session] section — secure should default to true
        let config: Config = toml::from_str("").unwrap();
        assert!(config.session.secure);
    }

    #[test]
    fn test_session_secure_can_be_disabled() {
        let toml_str = r#"
[session]
secure = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(!config.session.secure);
    }

    // --- Data source variant tests ---

    #[test]
    fn test_data_source_url_variant() {
        let toml_str = r#"
[data.api]
url = "https://api.example.com/data"
cache = 120
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        let source = config.data.get("api").expect("data.api should exist");

        match source {
            DataSource::Url { url, cache } => {
                assert_eq!(url, "https://api.example.com/data");
                assert_eq!(*cache, 120);
            }
            _ => panic!("Expected DataSource::Url variant"),
        }
    }

    #[test]
    fn test_data_source_url_default_cache() {
        let toml_str = r#"
[data.api]
url = "https://api.example.com/data"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        let source = config.data.get("api").unwrap();

        match source {
            DataSource::Url { cache, .. } => {
                assert_eq!(*cache, 300); // default_cache_ttl
            }
            _ => panic!("Expected DataSource::Url variant"),
        }
    }

    #[test]
    fn test_data_source_file_variant() {
        let toml_str = r#"
[data.local]
file = "data/products.json"
cache = 60
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        let source = config.data.get("local").unwrap();

        match source {
            DataSource::File { file, cache } => {
                assert_eq!(file, "data/products.json");
                assert_eq!(*cache, 60);
            }
            _ => panic!("Expected DataSource::File variant"),
        }
    }

    #[test]
    fn test_data_source_file_default_cache() {
        let toml_str = r#"
[data.local]
file = "data/products.json"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        let source = config.data.get("local").unwrap();

        match source {
            DataSource::File { cache, .. } => {
                assert_eq!(*cache, 300); // default_cache_ttl
            }
            _ => panic!("Expected DataSource::File variant"),
        }
    }

    #[test]
    fn test_data_source_simple_path_variant() {
        let toml_str = r#"
[data]
items = "data/items.json"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        let source = config.data.get("items").unwrap();

        match source {
            DataSource::SimplePath(path) => {
                assert_eq!(path, "data/items.json");
            }
            _ => panic!("Expected DataSource::SimplePath variant"),
        }
    }

    #[test]
    fn test_multiple_data_sources() {
        let toml_str = r#"
[data]
simple = "data/simple.json"

[data.api]
url = "https://api.example.com"

[data.local]
file = "data/local.json"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.data.len(), 3);
        assert!(config.data.contains_key("simple"));
        assert!(config.data.contains_key("api"));
        assert!(config.data.contains_key("local"));
    }

    // --- Datasource config tests ---

    #[test]
    fn test_datasources_default_empty() {
        let config = Config::default();
        assert!(config.datasources.is_empty());
    }

    #[test]
    fn test_parse_datasources_all_types() {
        let toml_str = r##"
[datasources.users]
type = "supabase"
project_url = "https://xxx.supabase.co"
api_key = "sk-xxx"

[datasources.content]
type = "d1"
account_id = "abc123"
api_token = "token123"
d1_database_id = "db-456"

[datasources.inventory]
type = "api"
url = "https://inventory.example.com"
headers = { Authorization = "Bearer tok123" }

[datasources.local_extra]
type = "sqlite"
path = "data/extra.db"
"##;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.datasources.len(), 4);

        let users = &config.datasources["users"];
        assert_eq!(users.r#type, DatasourceType::Supabase);
        assert_eq!(
            users.project_url.as_deref(),
            Some("https://xxx.supabase.co")
        );
        assert_eq!(users.api_key.as_deref(), Some("sk-xxx"));

        let content = &config.datasources["content"];
        assert_eq!(content.r#type, DatasourceType::D1);
        assert_eq!(content.account_id.as_deref(), Some("abc123"));
        assert_eq!(content.d1_database_id.as_deref(), Some("db-456"));

        let inventory = &config.datasources["inventory"];
        assert_eq!(inventory.r#type, DatasourceType::Api);
        assert_eq!(
            inventory.url.as_deref(),
            Some("https://inventory.example.com")
        );
        let headers = inventory.headers.as_ref().unwrap();
        assert_eq!(headers["Authorization"], "Bearer tok123");

        let local = &config.datasources["local_extra"];
        assert_eq!(local.r#type, DatasourceType::Sqlite);
        assert_eq!(local.path.as_deref(), Some("data/extra.db"));
    }

    // --- File loading tests ---

    #[test]
    fn test_load_nonexistent_file() {
        let result = Config::load("/nonexistent/path/what.toml");
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_toml_parsing() {
        let bad_toml = "this is not [valid toml ===";
        let result: std::result::Result<Config, _> = toml::from_str(bad_toml);
        assert!(result.is_err());
    }

    // --- Clone and Debug trait tests ---

    #[test]
    fn test_config_is_cloneable() {
        let config = Config::default();
        let cloned = config.clone();
        assert_eq!(cloned.server.port, config.server.port);
        assert_eq!(cloned.server.host, config.server.host);
    }

    #[test]
    fn test_config_is_debuggable() {
        let config = Config::default();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("Config"));
        assert!(debug_str.contains("8085"));
    }

    #[test]
    fn test_invalid_datasource_type_rejected() {
        let toml_str = r#"
[datasources.bad]
type = "mongodb"
url = "https://example.com"
"#;
        let result: std::result::Result<Config, _> = toml::from_str(toml_str);
        assert!(
            result.is_err(),
            "Unknown datasource type should fail deserialization"
        );
    }

    #[test]
    fn test_datasource_type_case_sensitive() {
        let toml_str = r#"
[datasources.bad]
type = "Supabase"
project_url = "https://xxx.supabase.co"
api_key = "key"
"#;
        let result: std::result::Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "Datasource type must be lowercase");
    }

    #[test]
    fn test_datasource_missing_type_field() {
        let toml_str = r#"
[datasources.notype]
url = "https://example.com"
"#;
        let result: std::result::Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "Datasource without type field should fail");
    }
}