autumn-admin-plugin 0.10.0

Out-of-the-box admin panel plugin for autumn-web applications
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
//! Admin panel model for `autumn_feature_flags`.
//!
//! Registers a flag management page at `/admin/feature-flags/` with:
//! - List view: key, enabled status, rollout %, actor allowlist, history link
//! - Edit view: toggle enabled, set `rollout_pct`, manage allowlists
//! - History tab: per-flag audit trail from `feature_flag_changes`

use serde_json::Value;

use crate::{
    AdminError, AdminField, AdminFieldKind, AdminFuture, AdminModel, ListParams, ListResult,
    SelectOption,
};

/// Admin panel model for feature flags.
///
/// # Postgres only
///
/// This model reads and writes `autumn_feature_flags`. That table is Postgres-only.
/// Its SQL uses `ILIKE`, `::type` casts and writable CTEs, which `SQLite` does
/// not have. On `SQLite` every method refuses with an error that names this
/// model. The plugin core is backend-agnostic: register your own
/// [`AdminModel`](crate::AdminModel)s there instead. See the crate README.
///
/// Register this model with the admin plugin to get a flag management UI
/// at `/admin/feature-flags/`:
///
/// ```rust,ignore
/// use autumn_admin_plugin::{prelude::*, AdminPlugin};
/// use autumn_admin_plugin::feature_flags::FeatureFlagAdminModel;
///
/// autumn_web::app()
///     .plugin(
///         AdminPlugin::new()
///             .register(FeatureFlagAdminModel::default()),
///     )
///     .run()
///     .await;
/// ```
#[derive(Debug, Default, Clone)]
pub struct FeatureFlagAdminModel;

impl AdminModel for FeatureFlagAdminModel {
    fn slug(&self) -> &'static str {
        "feature-flags"
    }

    fn display_name(&self) -> &'static str {
        "Feature Flag"
    }

    fn display_name_plural(&self) -> &'static str {
        "Feature Flags"
    }

    fn fields(&self) -> Vec<AdminField> {
        vec![
            AdminField::new("key", AdminFieldKind::Text)
                .label("Flag Key")
                .searchable(),
            AdminField::new("description", AdminFieldKind::TextArea)
                .label("Description")
                .optional()
                .searchable(),
            AdminField::new("enabled", AdminFieldKind::Boolean).label("Globally Enabled"),
            AdminField::new(
                "rollout_pct",
                AdminFieldKind::Select(vec![
                    SelectOption {
                        value: "0".into(),
                        label: "Off (0%)".into(),
                    },
                    SelectOption {
                        value: "10".into(),
                        label: "10%".into(),
                    },
                    SelectOption {
                        value: "25".into(),
                        label: "25%".into(),
                    },
                    SelectOption {
                        value: "50".into(),
                        label: "50%".into(),
                    },
                    SelectOption {
                        value: "75".into(),
                        label: "75%".into(),
                    },
                    SelectOption {
                        value: "100".into(),
                        label: "All (100%)".into(),
                    },
                ]),
            )
            .label("Rollout %")
            .optional(),
            AdminField::new("actor_allowlist", AdminFieldKind::TextArea)
                .label("Actor Allowlist (JSON array)")
                .optional()
                .hide_from_list(),
            AdminField::new("group_allowlist", AdminFieldKind::TextArea)
                .label("Group Allowlist (JSON array)")
                .optional()
                .hide_from_list(),
            AdminField::new("updated_at", AdminFieldKind::DateTime)
                .label("Last Updated")
                .readonly()
                .optional(),
        ]
    }

    fn record_display(&self, record: &Value) -> String {
        record
            .get("key")
            .and_then(|v| v.as_str())
            .map_or_else(|| "Feature Flag".to_owned(), |k| format!("Flag: {k}"))
    }

    fn list(
        &self,
        pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
        params: ListParams,
    ) -> AdminFuture<'_, ListResult> {
        use diesel_async::RunQueryDsl;

        let pool = pool.clone();
        Box::pin(async move {
            crate::traits::require_postgres("FeatureFlagAdminModel")?;
            let mut conn = pool
                .get()
                .await
                .map_err(|e| AdminError::Database(e.to_string()))?;

            let per_page = params.per_page;
            let (offset, limit) = params.sql_offset_limit();

            // Parameterized search — `%` alone matches everything (no search case).
            let search_pattern = format!("%{}%", params.search.as_deref().unwrap_or(""));

            let total: i64 = diesel::sql_query(
                "SELECT COUNT(*) FROM autumn_feature_flags \
                 WHERE (key ILIKE $1 OR COALESCE(description,'') ILIKE $1)",
            )
            .bind::<diesel::sql_types::Text, _>(&search_pattern)
            .get_result::<CountRow>(&mut conn)
            .await
            .map_or(0, |r| r.count);

            let records: Vec<Value> = diesel::sql_query(
                "SELECT id, key, description, enabled, rollout_pct, \
                        actor_allowlist, group_allowlist, updated_at \
                 FROM autumn_feature_flags \
                 WHERE (key ILIKE $1 OR COALESCE(description,'') ILIKE $1) \
                 ORDER BY key \
                 LIMIT $2 OFFSET $3",
            )
            .bind::<diesel::sql_types::Text, _>(&search_pattern)
            .bind::<diesel::sql_types::BigInt, _>(limit)
            .bind::<diesel::sql_types::BigInt, _>(offset)
            .load::<FlagRow>(&mut conn)
            .await
            .map(|rows| rows.into_iter().map(FlagRow::into_json).collect())
            .map_err(|e| AdminError::Database(e.to_string()))?;

            Ok(ListResult {
                total: u64::try_from(total).unwrap_or(0),
                page: params.page,
                per_page,
                records,
            })
        })
    }

    fn get(
        &self,
        pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
        id: i64,
    ) -> AdminFuture<'_, Option<Value>> {
        use diesel::prelude::*;
        use diesel_async::RunQueryDsl;

        let pool = pool.clone();
        Box::pin(async move {
            crate::traits::require_postgres("FeatureFlagAdminModel")?;
            let mut conn = pool
                .get()
                .await
                .map_err(|e| AdminError::Database(e.to_string()))?;

            diesel::sql_query(
                "SELECT id, key, description, enabled, rollout_pct, \
                        actor_allowlist, group_allowlist, updated_at \
                 FROM autumn_feature_flags WHERE id = $1",
            )
            .bind::<diesel::sql_types::BigInt, _>(id)
            .get_result::<FlagRow>(&mut conn)
            .await
            .optional()
            .map(|r| r.map(FlagRow::into_json))
            .map_err(|e| AdminError::Database(e.to_string()))
        })
    }

    fn create(
        &self,
        pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
        data: Value,
    ) -> AdminFuture<'_, Value> {
        use diesel_async::RunQueryDsl;

        let pool = pool.clone();
        Box::pin(async move {
            crate::traits::require_postgres("FeatureFlagAdminModel")?;
            let mut conn = pool
                .get()
                .await
                .map_err(|e| AdminError::Database(e.to_string()))?;

            let key = data
                .get("key")
                .and_then(Value::as_str)
                .ok_or_else(|| AdminError::Validation("'key' is required".into()))?;
            let enabled = data
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            // Select widget sends strings ("25"), direct API sends numbers.
            let mut rollout_pct = data
                .get("rollout_pct")
                .and_then(|v| {
                    v.as_i64()
                        .or_else(|| v.as_str().and_then(|s| s.parse::<i64>().ok()))
                })
                .unwrap_or(0)
                .clamp(0, 100);
            let description = data.get("description").and_then(Value::as_str);
            let actor_allowlist = validate_string_array(
                data.get("actor_allowlist")
                    .and_then(Value::as_str)
                    .unwrap_or("[]"),
                "actor_allowlist",
            )?;
            let group_allowlist = validate_string_array(
                data.get("group_allowlist")
                    .and_then(Value::as_str)
                    .unwrap_or("[]"),
                "group_allowlist",
            )?;

            // "Globally Enabled" with empty allowlists means globally on for all
            // actors — promote rollout_pct to 100 so the evaluator agrees.
            // When non-empty allowlists are provided, don't promote: the intent
            // is allowlist-only access, not global rollout.
            let has_allowlist = actor_allowlist != "[]" || group_allowlist != "[]";
            if enabled && rollout_pct == 0 && !has_allowlist {
                rollout_pct = 100;
            }

            let mutation = if enabled { "enabled" } else { "disabled" };

            // A CTE combines the INSERT and audit-log write into one atomic
            // statement.  Using a plain INSERT (no ON CONFLICT) means a duplicate
            // key rejects with a validation error rather than silently overwriting
            // a live flag via the admin "new record" form.
            let row = diesel::sql_query(
                "WITH inserted AS ( \
                     INSERT INTO autumn_feature_flags \
                         (key, description, enabled, rollout_pct, \
                          actor_allowlist, group_allowlist) \
                     VALUES ($1, $2, $3, $4, $5, $6) \
                     RETURNING id, key, description, enabled, rollout_pct, \
                               actor_allowlist, group_allowlist, updated_at \
                 ), \
                 _audit AS ( \
                     INSERT INTO feature_flag_changes (key, mutation, actor) \
                     SELECT key, $7, NULL FROM inserted \
                 ) \
                 SELECT id, key, description, enabled, rollout_pct, \
                        actor_allowlist, group_allowlist, updated_at \
                 FROM inserted",
            )
            .bind::<diesel::sql_types::Text, _>(key)
            .bind::<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>(
                description.map(str::to_owned),
            )
            .bind::<diesel::sql_types::Bool, _>(enabled)
            .bind::<diesel::sql_types::SmallInt, _>(i16::try_from(rollout_pct).unwrap_or(0))
            .bind::<diesel::sql_types::Text, _>(actor_allowlist)
            .bind::<diesel::sql_types::Text, _>(group_allowlist)
            .bind::<diesel::sql_types::Text, _>(mutation)
            .get_result::<FlagRow>(&mut conn)
            .await
            .map_err(|e| {
                if matches!(
                    e,
                    diesel::result::Error::DatabaseError(
                        diesel::result::DatabaseErrorKind::UniqueViolation,
                        _
                    )
                ) {
                    AdminError::Validation(format!("a flag with key '{key}' already exists"))
                } else {
                    AdminError::Database(e.to_string())
                }
            })?;

            Ok(FlagRow::into_json(row))
        })
    }

    fn update(
        &self,
        pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
        id: i64,
        data: Value,
    ) -> AdminFuture<'_, Value> {
        use diesel_async::RunQueryDsl;

        let pool = pool.clone();
        Box::pin(async move {
            crate::traits::require_postgres("FeatureFlagAdminModel")?;
            let mut conn = pool
                .get()
                .await
                .map_err(|e| AdminError::Database(e.to_string()))?;

            let key = data
                .get("key")
                .and_then(Value::as_str)
                .ok_or_else(|| AdminError::Validation("'key' is required".into()))?;
            let enabled = data
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let mut rollout_pct = data
                .get("rollout_pct")
                .and_then(|v| {
                    v.as_i64()
                        .or_else(|| v.as_str().and_then(|s| s.parse::<i64>().ok()))
                })
                .unwrap_or(0)
                .clamp(0, 100);
            let description = data.get("description").and_then(Value::as_str);
            let actor_allowlist = validate_string_array(
                data.get("actor_allowlist")
                    .and_then(Value::as_str)
                    .unwrap_or("[]"),
                "actor_allowlist",
            )?;
            let group_allowlist = validate_string_array(
                data.get("group_allowlist")
                    .and_then(Value::as_str)
                    .unwrap_or("[]"),
                "group_allowlist",
            )?;
            let has_allowlist = actor_allowlist != "[]" || group_allowlist != "[]";
            if enabled && rollout_pct == 0 && !has_allowlist {
                rollout_pct = 100;
            }

            let mutation = if enabled { "enabled" } else { "disabled" };

            // A CTE combines the key lookup, UPDATE, and both audit-log writes
            // into one atomic statement.  'old_row' reads the pre-update key so
            // a rename emits a 'deleted' invalidation for the old name;
            // '_audit_rename' is a no-op when the key is unchanged.
            let row = diesel::sql_query(
                "WITH old_row AS ( \
                     SELECT key FROM autumn_feature_flags WHERE id = $1 \
                 ), \
                 updated AS ( \
                     UPDATE autumn_feature_flags \
                     SET key = $2, description = $3, enabled = $4, rollout_pct = $5, \
                         actor_allowlist = $6, group_allowlist = $7, updated_at = NOW() \
                     WHERE id = $1 \
                     RETURNING id, key, description, enabled, rollout_pct, \
                               actor_allowlist, group_allowlist, updated_at \
                 ), \
                 _audit_rename AS ( \
                     INSERT INTO feature_flag_changes (key, mutation, actor) \
                     SELECT old_row.key, 'deleted', NULL \
                     FROM old_row \
                     WHERE old_row.key != $2 \
                 ), \
                 _audit_rename_breadcrumb AS ( \
                     INSERT INTO feature_flag_changes (key, mutation, actor) \
                     SELECT $2, 'renamed_from=' || old_row.key, NULL \
                     FROM old_row \
                     WHERE old_row.key != $2 \
                 ), \
                 _audit AS ( \
                     INSERT INTO feature_flag_changes (key, mutation, actor) \
                     SELECT key, $8, NULL FROM updated \
                 ) \
                 SELECT id, key, description, enabled, rollout_pct, \
                        actor_allowlist, group_allowlist, updated_at \
                 FROM updated",
            )
            .bind::<diesel::sql_types::BigInt, _>(id)
            .bind::<diesel::sql_types::Text, _>(key)
            .bind::<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>(
                description.map(str::to_owned),
            )
            .bind::<diesel::sql_types::Bool, _>(enabled)
            .bind::<diesel::sql_types::SmallInt, _>(i16::try_from(rollout_pct).unwrap_or(0))
            .bind::<diesel::sql_types::Text, _>(actor_allowlist)
            .bind::<diesel::sql_types::Text, _>(group_allowlist)
            .bind::<diesel::sql_types::Text, _>(mutation)
            .get_result::<FlagRow>(&mut conn)
            .await
            .map_err(|e| AdminError::Database(e.to_string()))?;

            Ok(FlagRow::into_json(row))
        })
    }

    fn delete(
        &self,
        pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
        id: i64,
    ) -> AdminFuture<'_, ()> {
        use diesel_async::RunQueryDsl;

        let pool = pool.clone();
        Box::pin(async move {
            crate::traits::require_postgres("FeatureFlagAdminModel")?;
            let mut conn = pool
                .get()
                .await
                .map_err(|e| AdminError::Database(e.to_string()))?;

            // A CTE combines the DELETE and audit-log write into one atomic
            // statement so that cache invalidation always fires together with
            // the row removal.
            diesel::sql_query(
                "WITH deleted AS ( \
                     DELETE FROM autumn_feature_flags WHERE id = $1 RETURNING key \
                 ), \
                 _audit AS ( \
                     INSERT INTO feature_flag_changes (key, mutation, actor) \
                     SELECT key, 'deleted', NULL FROM deleted \
                 ) \
                 SELECT COUNT(*) AS count FROM deleted",
            )
            .bind::<diesel::sql_types::BigInt, _>(id)
            .get_result::<CountRow>(&mut conn)
            .await
            .map_err(|e| AdminError::Database(e.to_string()))?;

            Ok(())
        })
    }

    fn execute_action(
        &self,
        pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
        action: &str,
        ids: Vec<i64>,
    ) -> AdminFuture<'_, u64> {
        // `FeatureFlagAdminModel` never declares soft delete
        // (`supports_soft_delete()` is the trait default, `false`), so
        // `actions()` (traits.rs) only ever offers `"delete"` — the admin UI
        // can't reach `"restore"` or `"purge"` for this model. Only `"delete"`
        // needs the batched fast path below; `"restore"`, `"purge"`, and any
        // other action name fall through to the shared
        // `dispatch_restore_purge_or_unhandled` helper (traits.rs), which a
        // direct or out-of-band `execute_action` call still reaches for the
        // same "does not support soft delete" (or "unhandled action") error
        // it always got.
        if action == "delete" {
            let pool = pool.clone();
            return Box::pin(async move {
                // The batched form binds a Postgres array. SQLite has no array
                // bind type. `backend_select!` keeps one arm and drops the
                // other, so the array never reaches the SQLite type-checker
                // (issue #2108).
                //
                // The SQLite arm keeps the crate compiling, and refuses.
                // FeatureFlagAdminModel is Postgres-only, so there is no
                // correct SQLite statement to fall back to.
                ::autumn_web::backend_select! {
                    pg => {{
                        use diesel_async::RunQueryDsl;

                        // Batch every id into ONE round trip instead of the trait
                        // default's one-CTE-per-id loop (an operator selecting
                        // hundreds of stale flags in the admin list and clicking
                        // "Delete selected" otherwise costs one statement, and one
                        // connection checkout, per flag). Same CTE shape as the
                        // single-row `delete()`: the audit INSERT's `SELECT key,
                        // 'deleted', NULL FROM deleted` already fans out to one row
                        // per id the `DELETE ... RETURNING key` actually removed, so
                        // widening the predicate to `id = ANY($1)` is enough — an id
                        // that doesn't exist contributes no row to `deleted` and so
                        // no audit row either, exactly like the loop it replaces.
                        //
                        // The returned count matches the *ids submitted*, not rows
                        // actually deleted, exactly like the loop this replaces
                        // (which incremented its counter once per id regardless of
                        // whether that id matched a row).
                        let mut conn = pool
                            .get()
                            .await
                            .map_err(|e| AdminError::Database(e.to_string()))?;
                        diesel::sql_query(
                            "WITH deleted AS ( \
                                 DELETE FROM autumn_feature_flags WHERE id = ANY($1) RETURNING key \
                             ), \
                             _audit AS ( \
                                 INSERT INTO feature_flag_changes (key, mutation, actor) \
                                 SELECT key, 'deleted', NULL FROM deleted \
                             ) \
                             SELECT COUNT(*) AS count FROM deleted",
                        )
                        .bind::<diesel::sql_types::Array<diesel::sql_types::BigInt>, _>(&ids)
                        .get_result::<CountRow>(&mut conn)
                        .await
                        .map_err(|e| AdminError::Database(e.to_string()))?;
                        Ok(u64::try_from(ids.len()).unwrap_or(u64::MAX))
                    }},
                    sqlite => {{
                        let _ = (&pool, &ids);
                        crate::traits::require_postgres("FeatureFlagAdminModel").map(|()| 0)
                    }},
                }
            });
        }

        crate::traits::dispatch_restore_purge_or_unhandled(self, pool, action, ids)
    }

    fn has_history(&self) -> bool {
        true
    }

    fn get_history<'a>(
        &'a self,
        pool: &'a diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
        record_id: i64,
        page: u64,
        per_page: u64,
    ) -> crate::AdminFuture<'a, crate::AdminHistoryPage> {
        use diesel::prelude::*;
        use diesel_async::RunQueryDsl;

        let pool = pool.clone();
        Box::pin(async move {
            crate::traits::require_postgres("FeatureFlagAdminModel")?;
            let mut conn = pool
                .get()
                .await
                .map_err(|e| AdminError::Database(e.to_string()))?;

            // Resolve the flag key by its stable integer id.
            let key: Option<String> =
                diesel::sql_query("SELECT key FROM autumn_feature_flags WHERE id = $1")
                    .bind::<diesel::sql_types::BigInt, _>(record_id)
                    .get_result::<KeyRow>(&mut conn)
                    .await
                    .optional()
                    .unwrap_or(None)
                    .map(|r| r.key);

            let Some(key) = key else {
                return Ok(crate::AdminHistoryPage {
                    entries: vec![],
                    total: 0,
                    page,
                    per_page,
                });
            };

            // Follow the full rename ancestry, not just one level.  Each rename
            // writes (new_key, 'renamed_from=old_key') into feature_flag_changes;
            // the recursive CTE walks those breadcrumbs until no more predecessors
            // are found, so an a→b→c chain shows all three keys' histories.
            let ancestor_cte = "WITH RECURSIVE ancestors AS ( \
                SELECT $1::text AS key \
                UNION \
                SELECT regexp_replace(ffc.mutation, '^renamed_from=', '') \
                FROM feature_flag_changes ffc \
                JOIN ancestors a ON ffc.key = a.key \
                WHERE ffc.mutation LIKE 'renamed_from=%' \
            )";

            let count: i64 = diesel::sql_query(format!(
                "{ancestor_cte} \
                 SELECT COUNT(*) FROM feature_flag_changes \
                 WHERE key IN (SELECT key FROM ancestors)",
            ))
            .bind::<diesel::sql_types::Text, _>(&key)
            .get_result::<CountRow>(&mut conn)
            .await
            .map_or(0, |r| r.count);

            let offset = (page.saturating_sub(1)) * per_page;
            let entries: Vec<crate::AdminHistoryEntry> = diesel::sql_query(format!(
                "{ancestor_cte} \
                 SELECT id, mutation AS op, actor, changed_at \
                 FROM feature_flag_changes \
                 WHERE key IN (SELECT key FROM ancestors) \
                 ORDER BY changed_at DESC \
                 LIMIT $2 OFFSET $3",
            ))
            .bind::<diesel::sql_types::Text, _>(&key)
            .bind::<diesel::sql_types::BigInt, _>(i64::try_from(per_page).unwrap_or(i64::MAX))
            .bind::<diesel::sql_types::BigInt, _>(i64::try_from(offset).unwrap_or(0))
            .load::<HistoryRow>(&mut conn)
            .await
            .unwrap_or_default()
            .into_iter()
            .map(history_row_to_entry)
            .collect();

            Ok(crate::AdminHistoryPage {
                entries,
                total: u64::try_from(count).unwrap_or(0),
                page,
                per_page,
            })
        })
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Parse `raw` as a JSON array of strings and re-serialise to canonical form.
///
/// An empty string is treated as `[]`.  A trailing comma (`["a",]`), a
/// non-array value, or mixed element types are all rejected with a validation
/// error so bad data never reaches the database column that later casts to
/// `::jsonb`.
fn validate_string_array(raw: &str, field: &str) -> Result<String, AdminError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Ok("[]".to_owned());
    }
    match serde_json::from_str::<Vec<serde_json::Value>>(trimmed) {
        Ok(arr) if arr.iter().all(serde_json::Value::is_string) => {
            Ok(serde_json::to_string(&arr).unwrap_or_else(|_| "[]".to_owned()))
        }
        Ok(_) => Err(AdminError::Validation(format!(
            "'{field}' must be a JSON array of strings (e.g. [\"user:42\"])"
        ))),
        Err(_) => Err(AdminError::Validation(format!(
            "'{field}' must be valid JSON (e.g. [\"user:42\"]); check for trailing commas"
        ))),
    }
}

// ── Row types ─────────────────────────────────────────────────────────────────

#[derive(diesel::QueryableByName)]
struct CountRow {
    #[diesel(sql_type = diesel::sql_types::BigInt)]
    count: i64,
}

#[derive(diesel::QueryableByName)]
struct KeyRow {
    #[diesel(sql_type = diesel::sql_types::Text)]
    key: String,
}

#[derive(diesel::QueryableByName)]
struct FlagRow {
    #[diesel(sql_type = diesel::sql_types::BigInt)]
    id: i64,
    #[diesel(sql_type = diesel::sql_types::Text)]
    key: String,
    #[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Text>)]
    description: Option<String>,
    #[diesel(sql_type = diesel::sql_types::Bool)]
    enabled: bool,
    #[diesel(sql_type = diesel::sql_types::SmallInt)]
    rollout_pct: i16,
    #[diesel(sql_type = diesel::sql_types::Text)]
    actor_allowlist: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    group_allowlist: String,
    #[diesel(sql_type = diesel::sql_types::Timestamp)]
    updated_at: chrono::NaiveDateTime,
}

impl FlagRow {
    fn into_json(self) -> Value {
        serde_json::json!({
            "id": self.id,
            "key": self.key,
            "description": self.description,
            "enabled": self.enabled,
            "rollout_pct": self.rollout_pct,
            "actor_allowlist": self.actor_allowlist,
            "group_allowlist": self.group_allowlist,
            "updated_at": self.updated_at.and_utc().to_rfc3339(),
        })
    }
}

// Echo clone class (autumn-admin-plugin::history_row_shape): `HistoryRow` and
// `history_row_to_entry` below are structurally identical to their namesakes
// in `experiments.rs` — same columns, same `actor` default. They have
// co-changed twice (commit 3d318b55: `changed_at` Timestamptz→Timestamp +
// `.and_utc()`; commit 10e9538e: pool type), but the surrounding query is not
// a clone: this model's `get_history` walks a rename-ancestry recursive CTE
// (`ancestor_cte` below) that `experiments.rs` has no equivalent for, so the
// two `get_history` bodies are a real, documented divergence, not an
// oversight. Two instances with no missed-fix defect is below Echo's merge
// bar (rule of three), so this is linked, not merged — keep the "cli"
// default and the column set in sync by hand;
// `history_row_to_entry_defaults_actor_to_cli` below pins the one invariant
// that matters.
#[derive(diesel::QueryableByName)]
struct HistoryRow {
    #[diesel(sql_type = diesel::sql_types::BigInt)]
    id: i64,
    #[diesel(sql_type = diesel::sql_types::Text)]
    op: String,
    #[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Text>)]
    actor: Option<String>,
    #[diesel(sql_type = diesel::sql_types::Timestamp)]
    changed_at: chrono::NaiveDateTime,
}

fn history_row_to_entry(r: HistoryRow) -> crate::AdminHistoryEntry {
    crate::AdminHistoryEntry {
        id: r.id,
        actor: r.actor.unwrap_or_else(|| "cli".to_owned()),
        op: r.op,
        request_id: None,
        changes: vec![],
        recorded_at: r.changed_at.and_utc(),
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    fn feature_flag_admin_model_slug_is_feature_flags() {
        let model = FeatureFlagAdminModel;
        assert_eq!(model.slug(), "feature-flags");
    }

    // Pins the one invariant `history_row_to_entry` shares with its
    // `experiments.rs` namesake (see the clone-class comment on `HistoryRow`
    // above): a NULL `actor` column reads as "cli" in the admin history tab.
    // If this drifts from `experiments.rs`'s copy, the two models' history
    // tabs would show different authorship for the same kind of
    // unattributed mutation.
    #[test]
    fn history_row_to_entry_defaults_actor_to_cli() {
        let row = HistoryRow {
            id: 1,
            op: "update".to_owned(),
            actor: None,
            changed_at: chrono::Utc::now().naive_utc(),
        };
        assert_eq!(history_row_to_entry(row).actor, "cli");
    }

    #[test]
    fn feature_flag_admin_model_has_correct_display_names() {
        let model = FeatureFlagAdminModel;
        assert_eq!(model.display_name(), "Feature Flag");
        assert_eq!(model.display_name_plural(), "Feature Flags");
    }

    #[test]
    fn feature_flag_admin_fields_include_required_columns() {
        let model = FeatureFlagAdminModel;
        let fields = model.fields();
        let names: Vec<&str> = fields.iter().map(|f| f.name).collect();
        assert!(names.contains(&"key"), "must have key field");
        assert!(names.contains(&"enabled"), "must have enabled field");
        assert!(
            names.contains(&"rollout_pct"),
            "must have rollout_pct field"
        );
        assert!(
            names.contains(&"actor_allowlist"),
            "must have actor_allowlist field"
        );
    }

    #[test]
    fn feature_flag_admin_model_has_history() {
        let model = FeatureFlagAdminModel;
        assert!(
            model.has_history(),
            "feature flag admin must expose history"
        );
    }

    #[test]
    fn record_display_uses_flag_key() {
        let model = FeatureFlagAdminModel;
        let record = serde_json::json!({"key": "beta_inbox", "enabled": false});
        assert_eq!(model.record_display(&record), "Flag: beta_inbox");
    }

    #[test]
    fn record_display_fallback_when_no_key() {
        let model = FeatureFlagAdminModel;
        let record = serde_json::json!({});
        assert_eq!(model.record_display(&record), "Feature Flag");
    }

    #[test]
    fn globally_enabled_with_zero_rollout_promotes_to_100() {
        // When the admin checks "Globally Enabled" but leaves Rollout % at the
        // default 0%, the saved rollout_pct must be 100 so the evaluator
        // (which requires rollout_pct >= 100 for global access) works correctly.
        //
        // This is a pure logic test — it doesn't hit the DB; it just verifies
        // that the promotion happens before the SQL bind.
        let enabled = true;
        let submitted_rollout: i64 = 0;
        let mut rollout_pct = submitted_rollout.clamp(0, 100);
        if enabled && rollout_pct == 0 {
            rollout_pct = 100;
        }
        assert_eq!(
            rollout_pct, 100,
            "enabled=true + rollout=0 must be promoted to rollout=100"
        );
    }

    #[test]
    fn globally_enabled_with_explicit_rollout_is_preserved() {
        // If the admin explicitly sets 25% rollout AND checks "Globally Enabled",
        // the rollout should stay at 25 (not promoted to 100).
        let enabled = true;
        let submitted_rollout: i64 = 25;
        let mut rollout_pct = submitted_rollout.clamp(0, 100);
        if enabled && rollout_pct == 0 {
            rollout_pct = 100;
        }
        assert_eq!(
            rollout_pct, 25,
            "enabled=true + explicit rollout=25 must be preserved"
        );
    }

    #[test]
    fn disabled_with_zero_rollout_is_not_promoted() {
        // Kill-switch (enabled=false) with rollout=0 must stay at 0.
        let enabled = false;
        let submitted_rollout: i64 = 0;
        let mut rollout_pct = submitted_rollout.clamp(0, 100);
        let has_allowlist = false;
        if enabled && rollout_pct == 0 && !has_allowlist {
            rollout_pct = 100;
        }
        assert_eq!(rollout_pct, 0, "kill-switch must not promote rollout_pct");
    }

    #[test]
    fn enabled_with_zero_rollout_and_non_empty_allowlist_is_not_promoted() {
        // When the admin creates an allowlist-only flag (enabled=true, rollout=0%,
        // actor_allowlist non-empty), rollout_pct must NOT be promoted to 100 —
        // that would expose the flag to everyone instead of just listed actors.
        let enabled = true;
        let submitted_rollout: i64 = 0;
        let actor_allowlist = r#"["user:42"]"#;
        let group_allowlist = "[]";
        let mut rollout_pct = submitted_rollout.clamp(0, 100);
        let has_allowlist = actor_allowlist != "[]" || group_allowlist != "[]";
        if enabled && rollout_pct == 0 && !has_allowlist {
            rollout_pct = 100;
        }
        assert_eq!(
            rollout_pct, 0,
            "allowlist-only flag must not have rollout_pct promoted to 100"
        );
    }

    #[test]
    fn validate_string_array_accepts_valid_array() {
        let result = validate_string_array(r#"["user:1","user:2"]"#, "actor_allowlist");
        assert!(result.is_ok(), "valid array must be accepted: {result:?}");
    }

    #[test]
    fn validate_string_array_accepts_empty_string_as_empty_array() {
        let result = validate_string_array("", "actor_allowlist");
        assert_eq!(result.unwrap(), "[]");
    }

    #[test]
    fn validate_string_array_rejects_trailing_comma() {
        let result = validate_string_array(r#"["user:42",]"#, "actor_allowlist");
        assert!(result.is_err(), "trailing comma must be rejected");
    }

    #[test]
    fn validate_string_array_rejects_non_array() {
        let result = validate_string_array("user:42", "actor_allowlist");
        assert!(result.is_err(), "bare string must be rejected");
    }

    #[test]
    fn validate_string_array_rejects_array_with_non_string_elements() {
        let result = validate_string_array("[1, 2, 3]", "actor_allowlist");
        assert!(result.is_err(), "integer elements must be rejected");
    }

    #[test]
    fn validate_string_array_normalises_output() {
        // Re-serialisation removes extra whitespace and produces canonical JSON.
        let result = validate_string_array(r#"[ "user:1" ,  "user:2" ]"#, "actor_allowlist");
        assert_eq!(result.unwrap(), r#"["user:1","user:2"]"#);
    }

    // ── execute_action fallthrough (restore/purge/unhandled) ──────────
    //
    // FeatureFlagAdminModel never supports soft delete, so these three
    // branches always error on the first id without touching the pool —
    // characterizing them pins the exact error text ahead of routing them
    // through the shared trait helper (Echo merge with TokenAdminModel).

    fn dummy_pool()
    -> diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection> {
        use diesel_async::pooled_connection::AsyncDieselConnectionManager;
        use diesel_async::pooled_connection::deadpool::Pool;
        let mgr = AsyncDieselConnectionManager::<::autumn_web::RuntimeConnection>::new(
            "postgresql://test",
        );
        Pool::builder(mgr).build().expect("build pool")
    }

    #[tokio::test]
    async fn execute_action_restore_errors_soft_delete_unsupported() {
        let model = FeatureFlagAdminModel;
        let pool = dummy_pool();
        let err = model
            .execute_action(&pool, "restore", vec![1, 2])
            .await
            .expect_err("restore must fail: model does not support soft delete");
        assert!(
            matches!(err, AdminError::Other(_)),
            "must be AdminError::Other: {err:?}"
        );
        assert!(format!("{err:?}").contains("does not support soft delete"));
    }

    #[tokio::test]
    async fn execute_action_purge_errors_soft_delete_unsupported() {
        let model = FeatureFlagAdminModel;
        let pool = dummy_pool();
        let err = model
            .execute_action(&pool, "purge", vec![1])
            .await
            .expect_err("purge must fail: model does not support soft delete");
        assert!(
            matches!(err, AdminError::Other(_)),
            "must be AdminError::Other: {err:?}"
        );
        assert!(format!("{err:?}").contains("does not support soft delete"));
    }

    #[tokio::test]
    async fn execute_action_unhandled_action_errors_with_action_name() {
        let model = FeatureFlagAdminModel;
        let pool = dummy_pool();
        let err = model
            .execute_action(&pool, "archive", vec![1])
            .await
            .expect_err("unknown action must error");
        assert!(
            matches!(err, AdminError::Other(_)),
            "must be AdminError::Other: {err:?}"
        );
        assert!(format!("{err:?}").contains("unhandled bulk action 'archive'"));
    }
}