waypoint-core 0.8.1

Lightweight, Flyway-compatible SQL migration library for PostgreSQL and MySQL
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
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
//! Configuration loading and resolution.
//!
//! Supports TOML config files, environment variables, and CLI overrides
//! with a defined priority order (CLI > env > TOML > defaults).

use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;

use serde::Deserialize;

use crate::error::{Result, WaypointError};

/// Helper macro to apply an optional owned value directly to a target field.
///
/// Replaces: `if let Some(v) = $opt { $target = v; }`
macro_rules! apply_option {
    ($opt:expr => $target:expr) => {
        if let Some(v) = $opt {
            $target = v;
        }
    };
}

/// Helper macro to apply an optional owned value, wrapping it in `Some()`.
///
/// Replaces: `if let Some(v) = $opt { $target = Some(v); }`
macro_rules! apply_option_some {
    ($opt:expr => $target:expr) => {
        if let Some(v) = $opt {
            $target = Some(v);
        }
    };
}

/// Helper macro to clone a borrowed optional value directly to a target field.
///
/// Replaces: `if let Some(ref v) = $opt { $target = v.clone(); }`
macro_rules! apply_option_clone {
    ($opt:expr => $target:expr) => {
        if let Some(ref v) = $opt {
            $target = v.clone();
        }
    };
}

/// Helper macro to clone a borrowed optional value, wrapping it in `Some()`.
///
/// Replaces: `if let Some(ref v) = $opt { $target = Some(v.clone()); }`
macro_rules! apply_option_some_clone {
    ($opt:expr => $target:expr) => {
        if let Some(ref v) = $opt {
            $target = Some(v.clone());
        }
    };
}

/// SSL/TLS connection mode.
///
/// These are libpq's `sslmode` values and carry libpq's meanings. In
/// particular `Require` encrypts but does **not** authenticate the server —
/// use [`SslMode::VerifyFull`] if you want the certificate chain and hostname
/// checked. libpq's `allow` is deliberately not supported; see `FromStr`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SslMode {
    /// Never use TLS.
    Disable,
    /// Try TLS first (without verifying the certificate), fall back to plaintext.
    #[default]
    Prefer,
    /// Require TLS, but do not verify the server certificate.
    Require,
    /// Require TLS and verify the certificate chain, but not the hostname.
    VerifyCa,
    /// Require TLS and verify both the certificate chain and the hostname.
    VerifyFull,
}

impl SslMode {
    /// Whether this mode verifies the server certificate chain at all.
    pub fn verifies_certificate(&self) -> bool {
        matches!(self, SslMode::VerifyCa | SslMode::VerifyFull)
    }

    /// Whether TLS is mandatory — i.e. a plaintext connection is not acceptable.
    pub fn requires_tls(&self) -> bool {
        matches!(
            self,
            SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull
        )
    }

    /// The canonical libpq spelling, for log and error messages.
    pub fn as_str(&self) -> &'static str {
        match self {
            SslMode::Disable => "disable",
            SslMode::Prefer => "prefer",
            SslMode::Require => "require",
            SslMode::VerifyCa => "verify-ca",
            SslMode::VerifyFull => "verify-full",
        }
    }
}

impl fmt::Display for SslMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for SslMode {
    type Err = WaypointError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        // Accept `-`, `_` and bare spellings so `verify-ca`, `verify_ca` and
        // `verifyca` all land in the same place.
        let normalized = s.to_lowercase().replace(['-', '_'], "");
        match normalized.as_str() {
            "disable" | "disabled" => Ok(SslMode::Disable),
            "prefer" => Ok(SslMode::Prefer),
            "require" | "required" => Ok(SslMode::Require),
            "verifyca" => Ok(SslMode::VerifyCa),
            "verifyfull" => Ok(SslMode::VerifyFull),
            // libpq's `allow` tries plaintext *first* and only then TLS. We do
            // not implement it, and aliasing it to `prefer` would quietly give
            // the opposite preference order, so reject it explicitly.
            "allow" => Err(WaypointError::ConfigError(
                "SSL mode 'allow' is not supported. Use 'prefer' to try TLS first \
                 and fall back to plaintext."
                    .to_string(),
            )),
            _ => Err(WaypointError::ConfigError(format!(
                "Invalid SSL mode '{}'. Use 'disable', 'prefer', 'require', \
                 'verify-ca', or 'verify-full'.",
                s
            ))),
        }
    }
}

/// Apply an `ssl_mode` string from one of the config layers, warning rather
/// than silently discarding a value that does not parse.
///
/// All three layers (TOML, env, CLI) route through here. The env and CLI paths
/// used to drop bad values with no message at all, which meant a typo in
/// `WAYPOINT_SSL_MODE` downgraded you to `prefer` invisibly.
fn apply_ssl_mode(target: &mut SslMode, value: &str, source: &str) {
    match value.parse() {
        Ok(mode) => *target = mode,
        Err(e) => log::warn!("{} (from {}); keeping '{}'.", e, source, target),
    }
}

/// Apply a numeric environment override, warning rather than silently
/// discarding a value that does not parse.
///
/// The numeric env vars used to be read with `if let Ok(v) = var(..) && let
/// Ok(n) = v.parse()`, which drops a bad value with no message at all. A very
/// ordinary mistake — `WAYPOINT_CONNECT_TIMEOUT=30s`, with the unit — left the
/// default silently in force while the operator believed the setting had taken
/// effect. Enum-valued vars already warned; this makes the numeric ones agree.
fn apply_env_number<T>(target: &mut T, value: &str, var: &str)
where
    T: std::str::FromStr + std::fmt::Display,
{
    match value.parse::<T>() {
        Ok(n) => *target = n,
        Err(_) => log::warn!(
            "Invalid {} '{}': expected a whole number; keeping '{}'.",
            var,
            value,
            target
        ),
    }
}

/// Parse a boolean environment variable, warning on anything unrecognised.
///
/// `WAYPOINT_BATCH_TRANSACTION` used to be `v == "1" || eq_ignore_ascii_case
/// ("true")` **assigned unconditionally**, so any other spelling — `yes`, `on`,
/// or a typo — silently set it to `false`, overriding a `batch_transaction =
/// true` in the TOML. Turning all-or-nothing mode off without saying so is
/// exactly the kind of quiet downgrade this codebase treats as a defect.
fn parse_env_bool(value: &str, var: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" => Some(false),
        other => {
            log::warn!(
                "Invalid {} '{}': expected one of 1/true/yes/on or 0/false/no/off; \
                 leaving the setting unchanged.",
                var,
                other
            );
            None
        }
    }
}

/// Top-level configuration for Waypoint.
#[derive(Debug, Clone, Default)]
pub struct WaypointConfig {
    /// Database connection settings (URL, host, port, credentials, etc.).
    pub database: DatabaseConfig,
    /// Migration behavior settings (locations, table name, ordering, etc.).
    pub migrations: MigrationSettings,
    /// SQL callback hook configuration for before/after migration phases.
    pub hooks: HooksConfig,
    /// Key-value placeholder substitutions applied to migration SQL.
    pub placeholders: HashMap<String, String>,
    /// Lint rule configuration.
    pub lint: LintConfig,
    /// Schema snapshot configuration for drift detection.
    pub snapshots: crate::commands::snapshot::SnapshotConfig,
    /// Pre-flight check configuration run before migrations.
    pub preflight: crate::preflight::PreflightConfig,
    /// Optional multi-database configuration for parallel migration targets.
    pub multi_database: Option<Vec<crate::multi::NamedDatabaseConfig>>,
    /// Guard (pre/post condition) configuration.
    pub guards: crate::guard::GuardsConfig,
    /// Auto-reversal generation configuration.
    pub reversals: crate::reversal::ReversalConfig,
    /// Safety analysis configuration.
    pub safety: crate::safety::SafetyConfig,
    /// Schema advisor configuration.
    pub advisor: crate::advisor::AdvisorConfig,
    /// Migration simulation configuration.
    pub simulation: SimulationConfig,
}

/// Database connection configuration.
#[derive(Clone)]
pub struct DatabaseConfig {
    /// Full connection URL (e.g., `postgres://user:pass@host/db`).
    pub url: Option<String>,
    /// Database server hostname.
    pub host: Option<String>,
    /// Database server port number.
    pub port: Option<u16>,
    /// Database user for authentication.
    pub user: Option<String>,
    /// Database password for authentication.
    pub password: Option<String>,
    /// Database name to connect to.
    pub database: Option<String>,
    /// Number of times to retry a failed connection (max 20).
    pub connect_retries: u32,
    /// SSL/TLS mode for the database connection.
    pub ssl_mode: SslMode,
    /// PEM file holding the CA certificate(s) used to verify the server.
    ///
    /// Mirrors libpq's `sslrootcert`: when set, these certificates **replace**
    /// the built-in Mozilla trust store rather than adding to it. Only
    /// consulted by the verifying modes (`verify-ca` / `verify-full`).
    pub ssl_root_cert: Option<PathBuf>,
    /// Connection timeout in seconds.
    pub connect_timeout_secs: u32,
    /// Statement timeout in seconds (0 means no timeout).
    pub statement_timeout_secs: u32,
    /// TCP keepalive interval in seconds (0 disables, default 120).
    pub keepalive_secs: u32,
    /// Which engine the host/port/user/database fields describe.
    ///
    /// Only consulted when `url` is unset. With a `url`, the engine is derived
    /// from its scheme (`postgres://` / `mysql://`). Defaults to PostgreSQL,
    /// which is what the field-based form always produced historically.
    pub engine: crate::dialect::DialectKind,
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            url: None,
            host: None,
            port: None,
            user: None,
            password: None,
            database: None,
            connect_retries: 0,
            ssl_mode: SslMode::Prefer,
            ssl_root_cert: None,
            connect_timeout_secs: 30,
            statement_timeout_secs: 0,
            keepalive_secs: 120,
            engine: crate::dialect::DialectKind::Postgres,
        }
    }
}

impl fmt::Debug for DatabaseConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DatabaseConfig")
            .field("url", &self.url.as_ref().map(|_| "[REDACTED]"))
            .field("host", &self.host)
            .field("port", &self.port)
            .field("user", &self.user)
            .field("password", &self.password.as_ref().map(|_| "[REDACTED]"))
            .field("database", &self.database)
            .field("connect_retries", &self.connect_retries)
            .field("ssl_mode", &self.ssl_mode)
            // A CA path is not a secret, so it prints plainly — knowing which
            // trust anchor was in play is the first thing you want when
            // debugging a handshake failure.
            .field("ssl_root_cert", &self.ssl_root_cert)
            .field("connect_timeout_secs", &self.connect_timeout_secs)
            .field("statement_timeout_secs", &self.statement_timeout_secs)
            .field("keepalive_secs", &self.keepalive_secs)
            .field("engine", &self.engine)
            .finish()
    }
}

/// Hook configuration for running SQL before/after migrations.
#[derive(Debug, Clone, Default)]
pub struct HooksConfig {
    /// SQL scripts to run once before the entire migration run.
    pub before_migrate: Vec<PathBuf>,
    /// SQL scripts to run once after the entire migration run.
    pub after_migrate: Vec<PathBuf>,
    /// SQL scripts to run before each individual migration.
    pub before_each_migrate: Vec<PathBuf>,
    /// SQL scripts to run after each individual migration.
    pub after_each_migrate: Vec<PathBuf>,
}

/// Lint configuration.
#[derive(Debug, Clone, Default)]
pub struct LintConfig {
    /// List of lint rule names to disable.
    pub disabled_rules: Vec<String>,
}

/// Migration behavior settings.
#[derive(Debug, Clone)]
pub struct MigrationSettings {
    /// Filesystem directories to scan for migration SQL files.
    pub locations: Vec<PathBuf>,
    /// Name of the schema history table.
    pub table: String,
    /// Database schema where the history table resides.
    pub schema: String,
    /// Whether to allow applying migrations with versions below the highest applied version.
    pub out_of_order: bool,
    /// Whether to validate already-applied migration checksums before migrating.
    pub validate_on_migrate: bool,
    /// Whether the `clean` command is allowed to run.
    pub clean_enabled: bool,
    /// Version to use when running the `baseline` command.
    pub baseline_version: String,
    /// Custom value for the `installed_by` column (defaults to database user).
    pub installed_by: Option<String>,
    /// Logical environment name (e.g., "production", "staging") for filtering.
    pub environment: Option<String>,
    /// Whether to use `@depends` directives to order migrations topologically.
    pub dependency_ordering: bool,
    /// Whether to display a progress indicator during migration.
    pub show_progress: bool,
    /// Whether to wrap all pending migrations in a single transaction (all-or-nothing).
    pub batch_transaction: bool,
}

impl Default for MigrationSettings {
    fn default() -> Self {
        Self {
            locations: vec![PathBuf::from("db/migrations")],
            table: "waypoint_schema_history".to_string(),
            schema: "public".to_string(),
            out_of_order: false,
            validate_on_migrate: true,
            clean_enabled: false,
            baseline_version: "1".to_string(),
            installed_by: None,
            environment: None,
            dependency_ordering: false,
            show_progress: true,
            batch_transaction: false,
        }
    }
}

/// Migration simulation configuration.
#[derive(Debug, Clone, Default)]
pub struct SimulationConfig {
    /// Whether to run simulation before migrate.
    pub simulate_before_migrate: bool,
}

// ── TOML deserialization structs ──

#[derive(Deserialize, Default)]
struct TomlConfig {
    database: Option<TomlDatabaseConfig>,
    migrations: Option<TomlMigrationSettings>,
    hooks: Option<TomlHooksConfig>,
    placeholders: Option<HashMap<String, String>>,
    lint: Option<TomlLintConfig>,
    snapshots: Option<TomlSnapshotConfig>,
    preflight: Option<TomlPreflightConfig>,
    databases: Option<Vec<TomlNamedDatabaseConfig>>,
    guards: Option<TomlGuardsConfig>,
    reversals: Option<TomlReversalConfig>,
    safety: Option<TomlSafetyConfig>,
    advisor: Option<TomlAdvisorConfig>,
    simulation: Option<TomlSimulationConfig>,
}

#[derive(Deserialize, Default)]
struct TomlDatabaseConfig {
    url: Option<String>,
    host: Option<String>,
    port: Option<u16>,
    user: Option<String>,
    password: Option<String>,
    database: Option<String>,
    connect_retries: Option<u32>,
    ssl_mode: Option<String>,
    ssl_root_cert: Option<String>,
    connect_timeout: Option<u32>,
    statement_timeout: Option<u32>,
    keepalive: Option<u32>,
    engine: Option<String>,
}

#[derive(Deserialize, Default)]
struct TomlMigrationSettings {
    locations: Option<Vec<String>>,
    table: Option<String>,
    schema: Option<String>,
    out_of_order: Option<bool>,
    validate_on_migrate: Option<bool>,
    clean_enabled: Option<bool>,
    baseline_version: Option<String>,
    installed_by: Option<String>,
    environment: Option<String>,
    dependency_ordering: Option<bool>,
    show_progress: Option<bool>,
    batch_transaction: Option<bool>,
}

#[derive(Deserialize, Default)]
struct TomlLintConfig {
    disabled_rules: Option<Vec<String>>,
}

#[derive(Deserialize, Default)]
struct TomlSnapshotConfig {
    directory: Option<String>,
    auto_snapshot_on_migrate: Option<bool>,
    max_snapshots: Option<usize>,
    strip_definer_mysql: Option<bool>,
}

#[derive(Deserialize, Default)]
struct TomlPreflightConfig {
    enabled: Option<bool>,
    max_replication_lag_mb: Option<i64>,
    max_replication_lag_secs: Option<i64>,
    long_query_threshold_secs: Option<i64>,
}

#[derive(Deserialize, Default)]
struct TomlNamedDatabaseConfig {
    name: Option<String>,
    url: Option<String>,
    depends_on: Option<Vec<String>>,
    migrations: Option<TomlMigrationSettings>,
    hooks: Option<TomlHooksConfig>,
    placeholders: Option<HashMap<String, String>>,
}

#[derive(Deserialize, Default)]
struct TomlHooksConfig {
    before_migrate: Option<Vec<String>>,
    after_migrate: Option<Vec<String>>,
    before_each_migrate: Option<Vec<String>>,
    after_each_migrate: Option<Vec<String>>,
}

#[derive(Deserialize, Default)]
struct TomlGuardsConfig {
    enabled: Option<bool>,
    on_require_fail: Option<String>,
}

#[derive(Deserialize, Default)]
struct TomlReversalConfig {
    enabled: Option<bool>,
    warn_data_loss: Option<bool>,
}

#[derive(Deserialize, Default)]
struct TomlSafetyConfig {
    enabled: Option<bool>,
    block_on_danger: Option<bool>,
    large_table_threshold: Option<i64>,
    huge_table_threshold: Option<i64>,
    refresh_stats_mysql: Option<bool>,
}

#[derive(Deserialize, Default)]
struct TomlAdvisorConfig {
    run_after_migrate: Option<bool>,
    disabled_rules: Option<Vec<String>>,
}

#[derive(Deserialize, Default)]
struct TomlSimulationConfig {
    simulate_before_migrate: Option<bool>,
}

/// CLI overrides that take highest priority.
#[derive(Debug, Default, Clone)]
pub struct CliOverrides {
    /// Override database connection URL.
    pub url: Option<String>,
    /// Override the database schema for the history table.
    pub schema: Option<String>,
    /// Override the schema history table name.
    pub table: Option<String>,
    /// Override migration file locations.
    pub locations: Option<Vec<PathBuf>>,
    /// Override whether out-of-order migrations are allowed.
    pub out_of_order: Option<bool>,
    /// Override whether to validate checksums on migrate.
    pub validate_on_migrate: Option<bool>,
    /// Override the baseline version string.
    pub baseline_version: Option<String>,
    /// Override the number of connection retries.
    pub connect_retries: Option<u32>,
    /// Override the SSL/TLS connection mode.
    pub ssl_mode: Option<String>,
    /// Override the CA certificate file used to verify the server.
    pub ssl_root_cert: Option<PathBuf>,
    /// Override the connection timeout in seconds.
    pub connect_timeout: Option<u32>,
    /// Override the statement timeout in seconds.
    pub statement_timeout: Option<u32>,
    /// Override the logical environment name.
    pub environment: Option<String>,
    /// Override whether to use dependency-based migration ordering.
    pub dependency_ordering: Option<bool>,
    /// Override TCP keepalive interval in seconds.
    pub keepalive: Option<u32>,
    /// Override batch transaction mode (all-or-nothing).
    pub batch_transaction: Option<bool>,
}

impl WaypointConfig {
    /// Load configuration with the following priority (highest wins):
    /// 1. CLI arguments
    /// 2. Environment variables
    /// 3. TOML config file
    /// 4. Built-in defaults
    pub fn load(config_path: Option<&str>, overrides: &CliOverrides) -> Result<Self> {
        let mut config = WaypointConfig::default();

        // Layer 3: TOML config file
        let toml_path = config_path.unwrap_or("waypoint.toml");
        if let Ok(content) = std::fs::read_to_string(toml_path) {
            // Warn if config file has overly permissive permissions (Unix only)
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if let Ok(meta) = std::fs::metadata(toml_path) {
                    let mode = meta.permissions().mode();
                    if mode & 0o077 != 0 {
                        log::warn!(
                            "Config file has overly permissive permissions. Consider chmod 600.; path={}, mode={:o}",
                            toml_path,
                            mode
                        );
                    }
                }
            }
            let toml_config: TomlConfig = toml::from_str(&content).map_err(|e| {
                WaypointError::ConfigError(format!(
                    "Failed to parse config file '{}': {}",
                    toml_path, e
                ))
            })?;
            config.apply_toml(toml_config);
        } else if config_path.is_some() {
            // If explicitly specified, error if not found
            return Err(WaypointError::ConfigError(format!(
                "Config file '{}' not found",
                toml_path
            )));
        }

        // Layer 2: Environment variables
        config.apply_env();

        // Layer 1: CLI overrides
        config.apply_cli(overrides);

        // Validate identifiers
        crate::db::validate_identifier(&config.migrations.schema)?;
        crate::db::validate_identifier(&config.migrations.table)?;

        // Cap connect_retries at 20
        if config.database.connect_retries > 20 {
            config.database.connect_retries = 20;
            log::warn!("connect_retries capped at 20");
        }

        Ok(config)
    }

    fn apply_toml(&mut self, toml: TomlConfig) {
        if let Some(db) = toml.database {
            apply_option_some!(db.url => self.database.url);
            apply_option_some!(db.host => self.database.host);
            apply_option_some!(db.port => self.database.port);
            apply_option_some!(db.user => self.database.user);
            apply_option_some!(db.password => self.database.password);
            apply_option_some!(db.database => self.database.database);
            apply_option!(db.connect_retries => self.database.connect_retries);
            if let Some(v) = db.ssl_mode {
                apply_ssl_mode(&mut self.database.ssl_mode, &v, "waypoint.toml");
            }
            if let Some(v) = db.ssl_root_cert {
                self.database.ssl_root_cert = Some(PathBuf::from(v));
            }
            apply_option!(db.connect_timeout => self.database.connect_timeout_secs);
            apply_option!(db.statement_timeout => self.database.statement_timeout_secs);
            apply_option!(db.keepalive => self.database.keepalive_secs);
            if let Some(v) = db.engine {
                match v.parse() {
                    Ok(kind) => self.database.engine = kind,
                    Err(_) => log::warn!(
                        "Invalid engine '{}' in config, using default 'postgres'. Valid values: postgres, mysql",
                        v
                    ),
                }
            }
        }

        if let Some(m) = toml.migrations {
            if let Some(v) = m.locations {
                self.migrations.locations = v.into_iter().map(|s| normalize_location(&s)).collect();
            }
            apply_option!(m.table => self.migrations.table);
            apply_option!(m.schema => self.migrations.schema);
            apply_option!(m.out_of_order => self.migrations.out_of_order);
            apply_option!(m.validate_on_migrate => self.migrations.validate_on_migrate);
            apply_option!(m.clean_enabled => self.migrations.clean_enabled);
            apply_option!(m.baseline_version => self.migrations.baseline_version);
            apply_option_some!(m.installed_by => self.migrations.installed_by);
            apply_option_some!(m.environment => self.migrations.environment);
            apply_option!(m.dependency_ordering => self.migrations.dependency_ordering);
            apply_option!(m.show_progress => self.migrations.show_progress);
            apply_option!(m.batch_transaction => self.migrations.batch_transaction);
        }

        if let Some(h) = toml.hooks {
            if let Some(v) = h.before_migrate {
                self.hooks.before_migrate = v.into_iter().map(PathBuf::from).collect();
            }
            if let Some(v) = h.after_migrate {
                self.hooks.after_migrate = v.into_iter().map(PathBuf::from).collect();
            }
            if let Some(v) = h.before_each_migrate {
                self.hooks.before_each_migrate = v.into_iter().map(PathBuf::from).collect();
            }
            if let Some(v) = h.after_each_migrate {
                self.hooks.after_each_migrate = v.into_iter().map(PathBuf::from).collect();
            }
        }

        if let Some(p) = toml.placeholders {
            self.placeholders.extend(p);
        }

        if let Some(l) = toml.lint {
            apply_option!(l.disabled_rules => self.lint.disabled_rules);
        }

        if let Some(s) = toml.snapshots {
            if let Some(v) = s.directory {
                self.snapshots.directory = PathBuf::from(v);
            }
            apply_option!(s.auto_snapshot_on_migrate => self.snapshots.auto_snapshot_on_migrate);
            apply_option!(s.max_snapshots => self.snapshots.max_snapshots);
            apply_option!(s.strip_definer_mysql => self.snapshots.strip_definer_mysql);
        }

        if let Some(p) = toml.preflight {
            apply_option!(p.enabled => self.preflight.enabled);
            apply_option!(p.max_replication_lag_mb => self.preflight.max_replication_lag_mb);
            apply_option!(p.max_replication_lag_secs => self.preflight.max_replication_lag_secs);
            apply_option!(p.long_query_threshold_secs => self.preflight.long_query_threshold_secs);
        }

        if let Some(g) = toml.guards {
            apply_option!(g.enabled => self.guards.enabled);
            if let Some(v) = g.on_require_fail {
                match v.parse() {
                    Ok(policy) => self.guards.on_require_fail = policy,
                    Err(_) => log::warn!(
                        "Invalid on_require_fail '{}' in config, using default 'error'. Valid values: error, warn, skip",
                        v
                    ),
                }
            }
        }

        if let Some(r) = toml.reversals {
            apply_option!(r.enabled => self.reversals.enabled);
            apply_option!(r.warn_data_loss => self.reversals.warn_data_loss);
        }

        if let Some(s) = toml.safety {
            apply_option!(s.enabled => self.safety.enabled);
            apply_option!(s.block_on_danger => self.safety.block_on_danger);
            apply_option!(s.large_table_threshold => self.safety.large_table_threshold);
            apply_option!(s.huge_table_threshold => self.safety.huge_table_threshold);
            apply_option!(s.refresh_stats_mysql => self.safety.refresh_stats_mysql);
        }

        if let Some(a) = toml.advisor {
            apply_option!(a.run_after_migrate => self.advisor.run_after_migrate);
            apply_option!(a.disabled_rules => self.advisor.disabled_rules);
        }

        if let Some(s) = toml.simulation {
            apply_option!(s.simulate_before_migrate => self.simulation.simulate_before_migrate);
        }

        if let Some(databases) = toml.databases {
            let mut named_dbs = Vec::new();
            for db in databases {
                let name = db.name.unwrap_or_default();
                // Inherit the top-level `[database]` tuning (ssl_mode,
                // timeouts, keepalive, retries) — those are transport policy
                // that should apply to every target — while clearing the
                // connection *identity* fields, which each entry supplies via
                // its own `url`. `[database]` is applied above, so `self` is
                // already populated at this point.
                let mut db_config = DatabaseConfig {
                    url: None,
                    host: None,
                    port: None,
                    user: None,
                    password: None,
                    database: None,
                    ..self.database.clone()
                };
                apply_option_some!(db.url => db_config.url);
                // Check for per-database env var
                let env_url_key = format!("WAYPOINT_DB_{}_URL", name.to_uppercase());
                if let Ok(url) = std::env::var(&env_url_key) {
                    db_config.url = Some(url);
                }

                // Start from the resolved top-level `[migrations]`, not from
                // defaults, so a `[databases.migrations]` block *overrides* the
                // global policy rather than replacing it. Starting from
                // `default()` meant a globally-set `table`, `schema`,
                // `out_of_order` or `validate_on_migrate` silently reverted for
                // every `[[databases]]` entry — writing the ledger to
                // `public.waypoint_schema_history` regardless of what the
                // top-level block said. `[database]` above already works this
                // way; `[migrations]` was the odd one out.
                //
                // `[migrations]` is applied before this block, so `self` is
                // fully resolved here.
                let mut mig_settings = self.migrations.clone();
                if let Some(m) = db.migrations {
                    if let Some(v) = m.locations {
                        mig_settings.locations =
                            v.into_iter().map(|s| normalize_location(&s)).collect();
                    }
                    apply_option!(m.table => mig_settings.table);
                    apply_option!(m.schema => mig_settings.schema);
                    apply_option!(m.out_of_order => mig_settings.out_of_order);
                    apply_option!(m.validate_on_migrate => mig_settings.validate_on_migrate);
                    apply_option!(m.clean_enabled => mig_settings.clean_enabled);
                    apply_option!(m.baseline_version => mig_settings.baseline_version);
                    apply_option_some!(m.installed_by => mig_settings.installed_by);
                    apply_option_some!(m.environment => mig_settings.environment);
                    apply_option!(m.dependency_ordering => mig_settings.dependency_ordering);
                    apply_option!(m.show_progress => mig_settings.show_progress);
                    apply_option!(m.batch_transaction => mig_settings.batch_transaction);
                }

                let mut hooks_config = HooksConfig::default();
                if let Some(h) = db.hooks {
                    if let Some(v) = h.before_migrate {
                        hooks_config.before_migrate = v.into_iter().map(PathBuf::from).collect();
                    }
                    if let Some(v) = h.after_migrate {
                        hooks_config.after_migrate = v.into_iter().map(PathBuf::from).collect();
                    }
                    if let Some(v) = h.before_each_migrate {
                        hooks_config.before_each_migrate =
                            v.into_iter().map(PathBuf::from).collect();
                    }
                    if let Some(v) = h.after_each_migrate {
                        hooks_config.after_each_migrate =
                            v.into_iter().map(PathBuf::from).collect();
                    }
                }

                named_dbs.push(crate::multi::NamedDatabaseConfig {
                    name,
                    database: db_config,
                    migrations: mig_settings,
                    hooks: hooks_config,
                    placeholders: db.placeholders.unwrap_or_default(),
                    depends_on: db.depends_on.unwrap_or_default(),
                });
            }
            self.multi_database = Some(named_dbs);
        }
    }

    fn apply_env(&mut self) {
        if let Ok(v) = std::env::var("WAYPOINT_DATABASE_URL") {
            self.database.url = Some(v);
        }
        if let Ok(v) = std::env::var("WAYPOINT_DATABASE_HOST") {
            self.database.host = Some(v);
        }
        if let Ok(v) = std::env::var("WAYPOINT_DATABASE_PORT") {
            match v.parse::<u16>() {
                Ok(port) => self.database.port = Some(port),
                Err(_) => log::warn!(
                    "Invalid WAYPOINT_DATABASE_PORT '{}': expected a port number; \
                     keeping the existing setting.",
                    v
                ),
            }
        }
        if let Ok(v) = std::env::var("WAYPOINT_DATABASE_USER") {
            self.database.user = Some(v);
        }
        if let Ok(v) = std::env::var("WAYPOINT_DATABASE_PASSWORD") {
            self.database.password = Some(v);
        }
        if let Ok(v) = std::env::var("WAYPOINT_DATABASE_NAME") {
            self.database.database = Some(v);
        }
        if let Ok(v) = std::env::var("WAYPOINT_CONNECT_RETRIES") {
            apply_env_number(
                &mut self.database.connect_retries,
                &v,
                "WAYPOINT_CONNECT_RETRIES",
            );
        }
        if let Ok(v) = std::env::var("WAYPOINT_SSL_MODE") {
            apply_ssl_mode(&mut self.database.ssl_mode, &v, "WAYPOINT_SSL_MODE");
        }
        if let Ok(v) = std::env::var("WAYPOINT_SSL_ROOT_CERT") {
            self.database.ssl_root_cert = Some(PathBuf::from(v));
        }
        if let Ok(v) = std::env::var("WAYPOINT_CONNECT_TIMEOUT") {
            apply_env_number(
                &mut self.database.connect_timeout_secs,
                &v,
                "WAYPOINT_CONNECT_TIMEOUT",
            );
        }
        if let Ok(v) = std::env::var("WAYPOINT_STATEMENT_TIMEOUT") {
            apply_env_number(
                &mut self.database.statement_timeout_secs,
                &v,
                "WAYPOINT_STATEMENT_TIMEOUT",
            );
        }
        if let Ok(v) = std::env::var("WAYPOINT_MIGRATIONS_LOCATIONS") {
            self.migrations.locations =
                v.split(',').map(|s| normalize_location(s.trim())).collect();
        }
        if let Ok(v) = std::env::var("WAYPOINT_MIGRATIONS_TABLE") {
            self.migrations.table = v;
        }
        if let Ok(v) = std::env::var("WAYPOINT_MIGRATIONS_SCHEMA") {
            self.migrations.schema = v;
        }

        if let Ok(v) = std::env::var("WAYPOINT_DATABASE_ENGINE") {
            match v.parse() {
                Ok(kind) => self.database.engine = kind,
                Err(_) => log::warn!(
                    "Invalid WAYPOINT_DATABASE_ENGINE '{}', using default 'postgres'",
                    v
                ),
            }
        }
        if let Ok(v) = std::env::var("WAYPOINT_KEEPALIVE") {
            apply_env_number(&mut self.database.keepalive_secs, &v, "WAYPOINT_KEEPALIVE");
        }
        if let Ok(v) = std::env::var("WAYPOINT_BATCH_TRANSACTION")
            && let Some(b) = parse_env_bool(&v, "WAYPOINT_BATCH_TRANSACTION")
        {
            self.migrations.batch_transaction = b;
        }
        if let Ok(v) = std::env::var("WAYPOINT_ENVIRONMENT") {
            self.migrations.environment = Some(v);
        }

        // Scan for placeholder env vars: WAYPOINT_PLACEHOLDER_{KEY}
        for (key, value) in std::env::vars() {
            if let Some(placeholder_key) = key.strip_prefix("WAYPOINT_PLACEHOLDER_") {
                self.placeholders
                    .insert(placeholder_key.to_lowercase(), value);
            }
        }
    }

    fn apply_cli(&mut self, overrides: &CliOverrides) {
        apply_option_some_clone!(overrides.url => self.database.url);
        apply_option_clone!(overrides.schema => self.migrations.schema);
        apply_option_clone!(overrides.table => self.migrations.table);
        apply_option_clone!(overrides.locations => self.migrations.locations);
        apply_option!(overrides.out_of_order => self.migrations.out_of_order);
        apply_option!(overrides.validate_on_migrate => self.migrations.validate_on_migrate);
        apply_option_clone!(overrides.baseline_version => self.migrations.baseline_version);
        apply_option!(overrides.connect_retries => self.database.connect_retries);
        if let Some(ref v) = overrides.ssl_mode {
            apply_ssl_mode(&mut self.database.ssl_mode, v, "--ssl-mode");
        }
        apply_option_some_clone!(overrides.ssl_root_cert => self.database.ssl_root_cert);
        apply_option!(overrides.connect_timeout => self.database.connect_timeout_secs);
        apply_option!(overrides.statement_timeout => self.database.statement_timeout_secs);
        apply_option_some_clone!(overrides.environment => self.migrations.environment);
        apply_option!(overrides.dependency_ordering => self.migrations.dependency_ordering);
        apply_option!(overrides.keepalive => self.database.keepalive_secs);
        apply_option!(overrides.batch_transaction => self.migrations.batch_transaction);
    }

    /// Build a connection string from the config.
    ///
    /// Prefers `url` if set; otherwise builds from the individual `host` /
    /// `port` / `user` / `password` / `database` fields, in the shape the
    /// configured [`DatabaseConfig::engine`] expects:
    ///
    /// - PostgreSQL → libpq key=value (`host=… port=… user=… dbname=…`)
    /// - MySQL → a `mysql://` URL, so that engine auto-detection still works
    ///
    /// Handles JDBC-style URLs by stripping the `jdbc:` prefix and extracting
    /// `user` and `password` query parameters.
    pub fn connection_string(&self) -> Result<String> {
        if let Some(ref url) = self.database.url {
            return Ok(normalize_jdbc_url(url));
        }

        let engine = self.database.engine;
        let host = self.database.host.as_deref().unwrap_or("localhost");
        let default_port = match engine {
            crate::dialect::DialectKind::Postgres => 5432,
            crate::dialect::DialectKind::Mysql => 3306,
        };
        let port = self.database.port.unwrap_or(default_port);
        let user =
            self.database.user.as_deref().ok_or_else(|| {
                WaypointError::ConfigError("Database user is required".to_string())
            })?;
        let database =
            self.database.database.as_deref().ok_or_else(|| {
                WaypointError::ConfigError("Database name is required".to_string())
            })?;

        match engine {
            crate::dialect::DialectKind::Mysql => {
                // A URL, not key=value: `DialectKind::from_url` has to be able
                // to route this to the MySQL backend. Credentials are
                // percent-encoded so specials in the password stay inside the
                // userinfo section.
                let auth = match self.database.password {
                    Some(ref password) => format!(
                        "{}:{}",
                        percent_encode_userinfo(user),
                        percent_encode_userinfo(password)
                    ),
                    None => percent_encode_userinfo(user),
                };
                Ok(format!("mysql://{}@{}:{}/{}", auth, host, port, database))
            }
            crate::dialect::DialectKind::Postgres => {
                let mut url = format!(
                    "host={} port={} user={} dbname={}",
                    host, port, user, database
                );
                if let Some(ref password) = self.database.password {
                    // Quote password to handle special characters (spaces, quotes, etc.)
                    let escaped = password.replace('\\', "\\\\").replace('\'', "\\'");
                    url.push_str(&format!(" password='{}'", escaped));
                }
                Ok(url)
            }
        }
    }
}

/// Percent-encode a URL userinfo component (username or password).
///
/// Everything outside the RFC 3986 unreserved set is escaped, so a password
/// containing `@`, `:`, `/`, `?` or `#` cannot break out of the userinfo
/// section and corrupt the authority. Hand-rolled rather than pulling in a
/// dependency for ~15 lines.
fn percent_encode_userinfo(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{:02X}", b)),
        }
    }
    out
}

/// Normalize a JDBC-style URL to a standard PostgreSQL connection string.
///
/// Handles:
///   - `jdbc:postgresql://host:port/db?user=x&password=y`  →  `postgresql://x:y@host:port/db`
///   - `postgresql://...` passed through as-is
///   - `postgres://...` passed through as-is
///
/// Credentials lifted out of the query string are percent-encoded on the way
/// into the authority; otherwise a password like `p@ss` would produce
/// `postgres://user:p@ss@host/db`, which does not parse as intended.
fn normalize_jdbc_url(url: &str) -> String {
    // Strip jdbc: prefix
    let url = url.strip_prefix("jdbc:").unwrap_or(url);

    // Parse query parameters for user/password if present
    if let Some((base, query)) = url.split_once('?') {
        let mut user = None;
        let mut password = None;
        let mut other_params = Vec::new();

        for param in query.split('&') {
            if let Some((key, value)) = param.split_once('=') {
                match key.to_lowercase().as_str() {
                    "user" => user = Some(value.to_string()),
                    "password" => password = Some(value.to_string()),
                    _ => other_params.push(param.to_string()),
                }
            }
        }

        // If we extracted user/password, rebuild the URL with credentials in the authority
        if (user.is_some() || password.is_some())
            && let Some(rest) = base
                .strip_prefix("postgresql://")
                .or_else(|| base.strip_prefix("postgres://"))
        {
            let scheme = if base.starts_with("postgresql://") {
                "postgresql"
            } else {
                "postgres"
            };

            let auth = match (user, password) {
                (Some(u), Some(p)) => format!(
                    "{}:{}@",
                    percent_encode_userinfo(&u),
                    percent_encode_userinfo(&p)
                ),
                (Some(u), None) => format!("{}@", percent_encode_userinfo(&u)),
                (None, Some(p)) => format!(":{}@", percent_encode_userinfo(&p)),
                (None, None) => String::new(),
            };

            let mut result = format!("{}://{}{}", scheme, auth, rest);
            if !other_params.is_empty() {
                result.push('?');
                result.push_str(&other_params.join("&"));
            }
            return result;
        }

        // No user/password in query, return with jdbc: stripped
        if other_params.is_empty() {
            return base.to_string();
        }
        return format!("{}?{}", base, other_params.join("&"));
    }

    url.to_string()
}

/// Strip `filesystem:` prefix from a location path (Flyway compatibility).
pub fn normalize_location(location: &str) -> PathBuf {
    let stripped = location.strip_prefix("filesystem:").unwrap_or(location);
    PathBuf::from(stripped)
}

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

    #[test]
    fn test_default_config() {
        let config = WaypointConfig::default();
        assert_eq!(config.migrations.table, "waypoint_schema_history");
        assert_eq!(config.migrations.schema, "public");
        assert!(!config.migrations.out_of_order);
        assert!(config.migrations.validate_on_migrate);
        assert!(!config.migrations.clean_enabled);
        assert_eq!(config.migrations.baseline_version, "1");
        assert_eq!(
            config.migrations.locations,
            vec![PathBuf::from("db/migrations")]
        );
    }

    #[test]
    fn test_connection_string_from_url() {
        let mut config = WaypointConfig::default();
        config.database.url = Some("postgres://user:pass@localhost/db".to_string());
        assert_eq!(
            config.connection_string().unwrap(),
            "postgres://user:pass@localhost/db"
        );
    }

    #[test]
    fn test_connection_string_from_fields() {
        let mut config = WaypointConfig::default();
        config.database.host = Some("myhost".to_string());
        config.database.port = Some(5433);
        config.database.user = Some("myuser".to_string());
        config.database.database = Some("mydb".to_string());
        config.database.password = Some("secret".to_string());

        let conn = config.connection_string().unwrap();
        assert!(conn.contains("host=myhost"));
        assert!(conn.contains("port=5433"));
        assert!(conn.contains("user=myuser"));
        assert!(conn.contains("dbname=mydb"));
        assert!(conn.contains("password='secret'"));
    }

    #[test]
    fn test_connection_string_missing_user() {
        let mut config = WaypointConfig::default();
        config.database.database = Some("mydb".to_string());
        assert!(config.connection_string().is_err());
    }

    #[test]
    fn test_cli_overrides() {
        let mut config = WaypointConfig::default();
        let overrides = CliOverrides {
            url: Some("postgres://override@localhost/db".to_string()),
            schema: Some("custom_schema".to_string()),
            table: Some("custom_table".to_string()),
            locations: Some(vec![PathBuf::from("custom/path")]),
            out_of_order: Some(true),
            validate_on_migrate: Some(false),
            baseline_version: Some("5".to_string()),
            connect_retries: None,
            ssl_mode: None,
            ssl_root_cert: None,
            connect_timeout: None,
            statement_timeout: None,
            environment: None,
            dependency_ordering: None,
            keepalive: None,
            batch_transaction: None,
        };

        config.apply_cli(&overrides);

        assert_eq!(
            config.database.url.as_deref(),
            Some("postgres://override@localhost/db")
        );
        assert_eq!(config.migrations.schema, "custom_schema");
        assert_eq!(config.migrations.table, "custom_table");
        assert_eq!(
            config.migrations.locations,
            vec![PathBuf::from("custom/path")]
        );
        assert!(config.migrations.out_of_order);
        assert!(!config.migrations.validate_on_migrate);
        assert_eq!(config.migrations.baseline_version, "5");
    }

    #[test]
    fn test_toml_parsing() {
        let toml_str = r#"
[database]
url = "postgres://user:pass@localhost/mydb"

[migrations]
table = "my_history"
schema = "app"
out_of_order = true
locations = ["sql/migrations", "sql/seeds"]

[placeholders]
env = "production"
app_name = "myapp"
"#;

        let toml_config: TomlConfig = toml::from_str(toml_str).unwrap();
        let mut config = WaypointConfig::default();
        config.apply_toml(toml_config);

        assert_eq!(
            config.database.url.as_deref(),
            Some("postgres://user:pass@localhost/mydb")
        );
        assert_eq!(config.migrations.table, "my_history");
        assert_eq!(config.migrations.schema, "app");
        assert!(config.migrations.out_of_order);
        assert_eq!(
            config.migrations.locations,
            vec![PathBuf::from("sql/migrations"), PathBuf::from("sql/seeds")]
        );
        assert_eq!(config.placeholders.get("env").unwrap(), "production");
        assert_eq!(config.placeholders.get("app_name").unwrap(), "myapp");
    }

    #[test]
    fn test_normalize_jdbc_url_with_credentials() {
        let url = "jdbc:postgresql://myhost:5432/mydb?user=admin&password=secret";
        assert_eq!(
            normalize_jdbc_url(url),
            "postgresql://admin:secret@myhost:5432/mydb"
        );
    }

    #[test]
    fn test_normalize_jdbc_url_user_only() {
        let url = "jdbc:postgresql://myhost:5432/mydb?user=admin";
        assert_eq!(
            normalize_jdbc_url(url),
            "postgresql://admin@myhost:5432/mydb"
        );
    }

    #[test]
    fn test_normalize_jdbc_url_strips_jdbc_prefix() {
        let url = "jdbc:postgresql://myhost:5432/mydb";
        assert_eq!(normalize_jdbc_url(url), "postgresql://myhost:5432/mydb");
    }

    #[test]
    fn test_normalize_jdbc_url_passthrough() {
        let url = "postgresql://user:pass@myhost:5432/mydb";
        assert_eq!(normalize_jdbc_url(url), url);
    }

    #[test]
    fn test_normalize_jdbc_url_preserves_other_params() {
        let url = "jdbc:postgresql://myhost:5432/mydb?user=admin&password=secret&sslmode=require";
        assert_eq!(
            normalize_jdbc_url(url),
            "postgresql://admin:secret@myhost:5432/mydb?sslmode=require"
        );
    }

    #[test]
    fn test_normalize_location_filesystem_prefix() {
        assert_eq!(
            normalize_location("filesystem:/flyway/sql"),
            PathBuf::from("/flyway/sql")
        );
    }

    #[test]
    fn test_normalize_location_plain_path() {
        assert_eq!(
            normalize_location("/my/migrations"),
            PathBuf::from("/my/migrations")
        );
    }

    #[test]
    fn test_normalize_location_relative() {
        assert_eq!(
            normalize_location("filesystem:db/migrations"),
            PathBuf::from("db/migrations")
        );
    }

    #[test]
    fn test_connection_string_password_special_chars() {
        let config = WaypointConfig {
            database: DatabaseConfig {
                host: Some("localhost".to_string()),
                port: Some(5432),
                user: Some("admin".to_string()),
                database: Some("mydb".to_string()),
                password: Some("p@ss'w ord".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        let conn = config.connection_string().unwrap();
        assert!(conn.contains("password='p@ss\\'w ord'"));
    }

    #[test]
    fn test_connection_string_mysql_from_fields() {
        let config = WaypointConfig {
            database: DatabaseConfig {
                engine: crate::dialect::DialectKind::Mysql,
                host: Some("db.internal".to_string()),
                user: Some("app".to_string()),
                password: Some("s3cr3t".to_string()),
                database: Some("shop".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        // Defaults to the MySQL port and emits a URL the engine detector routes.
        assert_eq!(
            config.connection_string().unwrap(),
            "mysql://app:s3cr3t@db.internal:3306/shop"
        );
        assert_eq!(
            crate::dialect::DialectKind::from_url(&config.connection_string().unwrap()),
            Some(crate::dialect::DialectKind::Mysql)
        );
    }

    #[test]
    fn test_connection_string_mysql_percent_encodes_password() {
        let config = WaypointConfig {
            database: DatabaseConfig {
                engine: crate::dialect::DialectKind::Mysql,
                host: Some("h".to_string()),
                port: Some(13306),
                user: Some("u".to_string()),
                password: Some("p@ss/word".to_string()),
                database: Some("d".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config.connection_string().unwrap(),
            "mysql://u:p%40ss%2Fword@h:13306/d"
        );
    }

    #[test]
    fn test_normalize_jdbc_url_percent_encodes_credentials() {
        // An unencoded `@` in the password would break the authority.
        let url = "jdbc:postgresql://myhost:5432/mydb?user=adm%69n&password=p@ss";
        assert_eq!(
            normalize_jdbc_url(url),
            "postgresql://adm%2569n:p%40ss@myhost:5432/mydb"
        );
    }

    #[test]
    fn test_engine_defaults_to_postgres() {
        let config = WaypointConfig::default();
        assert_eq!(
            config.database.engine,
            crate::dialect::DialectKind::Postgres
        );
    }

    #[test]
    fn test_toml_engine_key() {
        let toml_str = r#"
[database]
engine = "mysql"
host = "localhost"
user = "root"
database = "app"
"#;
        let toml_config: TomlConfig = toml::from_str(toml_str).unwrap();
        let mut config = WaypointConfig::default();
        config.apply_toml(toml_config);
        assert_eq!(config.database.engine, crate::dialect::DialectKind::Mysql);
        assert!(config.connection_string().unwrap().starts_with("mysql://"));
    }

    #[test]
    fn test_ssl_mode_parses_the_libpq_ladder() {
        for (input, want) in [
            ("disable", SslMode::Disable),
            ("DISABLE", SslMode::Disable),
            ("disabled", SslMode::Disable),
            ("prefer", SslMode::Prefer),
            ("require", SslMode::Require),
            ("required", SslMode::Require),
            ("verify-ca", SslMode::VerifyCa),
            ("verify_ca", SslMode::VerifyCa),
            ("verifyca", SslMode::VerifyCa),
            ("Verify-Full", SslMode::VerifyFull),
            ("verify_full", SslMode::VerifyFull),
        ] {
            assert_eq!(input.parse::<SslMode>().unwrap(), want, "input: {}", input);
        }
    }

    #[test]
    fn test_ssl_mode_rejects_allow_and_names_the_alternative() {
        // libpq's `allow` prefers plaintext; aliasing it to `prefer` would
        // silently invert the preference order, so it is rejected outright.
        let err = "allow".parse::<SslMode>().unwrap_err().to_string();
        assert!(err.contains("not supported"), "got: {}", err);
        assert!(err.contains("prefer"), "must name the replacement: {}", err);
    }

    #[test]
    fn test_ssl_mode_rejects_unknown_values() {
        assert!("verify".parse::<SslMode>().is_err());
        assert!("".parse::<SslMode>().is_err());
        let err = "banana".parse::<SslMode>().unwrap_err().to_string();
        assert!(
            err.contains("verify-full"),
            "should list valid modes: {}",
            err
        );
    }

    #[test]
    fn test_ssl_mode_predicates_form_a_ladder() {
        use SslMode::*;
        let ladder = [Disable, Prefer, Require, VerifyCa, VerifyFull];
        assert_eq!(
            ladder.map(|m| m.requires_tls()),
            [false, false, true, true, true]
        );
        assert_eq!(
            ladder.map(|m| m.verifies_certificate()),
            [false, false, false, true, true]
        );
    }

    #[test]
    fn test_ssl_root_cert_defaults_to_none() {
        assert_eq!(WaypointConfig::default().database.ssl_root_cert, None);
    }

    #[test]
    fn test_toml_ssl_root_cert_key() {
        let toml_str = r#"
[database]
url = "postgres://user@localhost/mydb"
ssl_mode = "verify-full"
ssl_root_cert = "/etc/ssl/certs/internal-ca.pem"
"#;
        let toml_config: TomlConfig = toml::from_str(toml_str).unwrap();
        let mut config = WaypointConfig::default();
        config.apply_toml(toml_config);
        assert_eq!(config.database.ssl_mode, SslMode::VerifyFull);
        assert_eq!(
            config.database.ssl_root_cert,
            Some(PathBuf::from("/etc/ssl/certs/internal-ca.pem"))
        );
    }

    #[test]
    fn test_invalid_toml_ssl_mode_keeps_the_default() {
        let toml_str = r#"
[database]
url = "postgres://user@localhost/mydb"
ssl_mode = "verify-fulll"
"#;
        let toml_config: TomlConfig = toml::from_str(toml_str).unwrap();
        let mut config = WaypointConfig::default();
        config.apply_toml(toml_config);
        assert_eq!(config.database.ssl_mode, SslMode::Prefer);
    }

    #[test]
    fn test_multi_database_inherits_tls_settings() {
        // `[[databases]]` entries carry the top-level transport policy, so a
        // custom CA configured once applies to every target.
        let toml_str = r#"
[database]
ssl_mode = "verify-full"
ssl_root_cert = "/etc/ssl/ca.pem"

[[databases]]
name = "orders"
url = "postgres://user@localhost/orders"
"#;
        let toml_config: TomlConfig = toml::from_str(toml_str).unwrap();
        let mut config = WaypointConfig::default();
        config.apply_toml(toml_config);
        let multi = config.multi_database.expect("expected a multi-db config");
        let db = &multi[0];
        assert_eq!(db.database.ssl_mode, SslMode::VerifyFull);
        assert_eq!(
            db.database.ssl_root_cert,
            Some(PathBuf::from("/etc/ssl/ca.pem"))
        );
    }

    #[test]
    fn test_multi_database_inherits_top_level_migration_settings() {
        // The `[database]` twin above proves transport policy is inherited.
        // `[migrations]` must behave the same way: a `[[databases]]` entry
        // *overrides* the global block, it does not replace it with defaults.
        // Otherwise a globally-configured history table or schema silently
        // reverts per database — writing the ledger to the wrong place.
        let toml_str = r#"
[migrations]
table = "custom_history"
schema = "app"
out_of_order = true
validate_on_migrate = false

[[databases]]
name = "orders"
url = "postgres://user@localhost/orders"

[databases.migrations]
locations = ["db/orders"]
"#;
        let toml_config: TomlConfig = toml::from_str(toml_str).unwrap();
        let mut config = WaypointConfig::default();
        config.apply_toml(toml_config);
        let multi = config.multi_database.expect("expected a multi-db config");
        let db = &multi[0];

        // Overridden per database.
        assert_eq!(db.migrations.locations, vec![PathBuf::from("db/orders")]);
        // Inherited from the top-level block.
        assert_eq!(db.migrations.table, "custom_history");
        assert_eq!(db.migrations.schema, "app");
        assert!(db.migrations.out_of_order);
        assert!(!db.migrations.validate_on_migrate);
    }

    #[test]
    fn test_apply_env_number_keeps_previous_value_on_garbage() {
        // The bug this replaces: `WAYPOINT_CONNECT_TIMEOUT=30s` parsed as a
        // number fails, and the old let-chain silently kept the default with no
        // message at all.
        let mut timeout: u32 = 30;
        apply_env_number(&mut timeout, "45", "WAYPOINT_CONNECT_TIMEOUT");
        assert_eq!(timeout, 45, "a valid value must be applied");

        apply_env_number(&mut timeout, "30s", "WAYPOINT_CONNECT_TIMEOUT");
        assert_eq!(
            timeout, 45,
            "a unit suffix must not silently reset the value"
        );

        apply_env_number(&mut timeout, "", "WAYPOINT_CONNECT_TIMEOUT");
        assert_eq!(timeout, 45);
    }

    #[test]
    fn test_parse_env_bool_accepts_common_spellings() {
        for v in ["1", "true", "TRUE", "yes", "on", " True "] {
            assert_eq!(parse_env_bool(v, "T"), Some(true), "input: {v:?}");
        }
        for v in ["0", "false", "FALSE", "no", "off"] {
            assert_eq!(parse_env_bool(v, "T"), Some(false), "input: {v:?}");
        }
    }

    #[test]
    fn test_parse_env_bool_rejects_unknown_instead_of_defaulting_to_false() {
        // The old expression coerced anything unrecognised to `false`, so a
        // typo silently turned off all-or-nothing batch mode that the TOML had
        // switched on. `None` means "leave the setting alone".
        for v in ["y", "enabled", "maybe", "tru"] {
            assert_eq!(
                parse_env_bool(v, "WAYPOINT_BATCH_TRANSACTION"),
                None,
                "input: {v:?}"
            );
        }
    }
}