heldar-entry 0.1.5

Heldar Access Control — generic ANPR authorization, vehicle/visitor/watchlist registry, guard workflow, and entry reports for gated-entry deployments. Built on the heldar-kernel platform.
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
//! Stage 4 access-control surface: registered vehicles, visitor passes (+ check-in/out), watchlist,
//! the canonical entry-event feed with a guard confirm/reject workflow, and reports (daily entry
//! log, exceptions, audit). Reads require any authenticated principal; registry mutations require
//! manager+, gate operations require guard+, and the audit report requires manager+.

use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::routing::{get, post};
use axum::{Json, Router};
use chrono::{DateTime, Duration, Utc};
use serde::Deserialize;
use serde_json::{json, Value};
use sqlx::types::Json as SqlxJson;
use uuid::Uuid;

use crate::anpr::normalize_plate;
use crate::models::{
    AuditLog, EntryEvent, Vehicle, VehicleCreate, VehicleUpdate, VisitorPass, VisitorPassCreate,
    VisitorPassUpdate, Watchlist, WatchlistCreate, WatchlistUpdate,
};
use heldar_kernel::auth::{self, Principal};
use heldar_kernel::error::{AppError, AppResult};
use heldar_kernel::state::AppState;

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/api/v1/vehicles", get(list_vehicles).post(create_vehicle))
        .route(
            "/api/v1/vehicles/{id}",
            get(get_vehicle)
                .patch(update_vehicle)
                .delete(delete_vehicle),
        )
        .route("/api/v1/passes", get(list_passes).post(create_pass))
        .route(
            "/api/v1/passes/{id}",
            get(get_pass).patch(update_pass).delete(delete_pass),
        )
        .route("/api/v1/passes/{id}/checkin", post(checkin_pass))
        .route("/api/v1/passes/{id}/checkout", post(checkout_pass))
        .route("/api/v1/watchlist", get(list_watchlist).post(create_watch))
        .route(
            "/api/v1/watchlist/{id}",
            axum::routing::patch(update_watch).delete(delete_watch),
        )
        .route("/api/v1/entry-events", get(list_entry_events))
        .route("/api/v1/entry-events/{id}", get(get_entry_event))
        .route("/api/v1/entry-events/{id}/confirm", post(confirm_event))
        .route("/api/v1/entry-events/{id}/reject", post(reject_event))
        .route("/api/v1/reports/entry-log", get(report_entry_log))
        .route("/api/v1/reports/exceptions", get(report_exceptions))
        .route("/api/v1/audit", get(list_audit))
}

const OWNER_TYPES: [&str; 5] = ["student", "staff", "resident", "contractor", "visitor"];
const WATCH_KINDS: [&str; 3] = ["block", "vip", "alert"];
const SEVERITIES: [&str; 3] = ["info", "warning", "critical"];

fn parse_opt_ts(s: &Option<String>, field: &str) -> AppResult<Option<DateTime<Utc>>> {
    match s {
        Some(v) if !v.trim().is_empty() => heldar_kernel::util::parse_rfc3339(v)
            .map(Some)
            .ok_or_else(|| AppError::BadRequest(format!("invalid `{field}` timestamp"))),
        _ => Ok(None),
    }
}

// ---- Vehicles ------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct VehicleQuery {
    plate: Option<String>,
    owner_type: Option<String>,
    q: Option<String>,
    limit: Option<i64>,
}

async fn list_vehicles(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<VehicleQuery>,
) -> AppResult<Json<Vec<Vehicle>>> {
    principal.require(principal.can_view(), "view vehicles")?;
    let limit = q.limit.unwrap_or(200).clamp(1, 2000);
    let plate_norm = q.plate.as_deref().map(normalize_plate);
    let like = q.q.as_deref().map(|s| format!("%{}%", s.trim()));
    let rows = sqlx::query_as::<_, Vehicle>(
        "SELECT * FROM vehicles
          WHERE (? IS NULL OR plate_norm = ?)
            AND (? IS NULL OR owner_type = ?)
            AND (? IS NULL OR owner_name LIKE ? OR plate LIKE ? OR owner_ref LIKE ?)
          ORDER BY created_at DESC LIMIT ?",
    )
    .bind(&plate_norm)
    .bind(&plate_norm)
    .bind(&q.owner_type)
    .bind(&q.owner_type)
    .bind(&like)
    .bind(&like)
    .bind(&like)
    .bind(&like)
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(rows))
}

async fn get_vehicle(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<Json<Vehicle>> {
    principal.require(principal.can_view(), "view vehicles")?;
    let v = sqlx::query_as::<_, Vehicle>("SELECT * FROM vehicles WHERE id = ?")
        .bind(&id)
        .fetch_optional(&st.pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("vehicle {id} not found")))?;
    Ok(Json(v))
}

async fn create_vehicle(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<VehicleCreate>,
) -> AppResult<(StatusCode, Json<Vehicle>)> {
    principal.require(principal.can_manage_registry(), "register vehicles")?;
    let plate_norm = normalize_plate(&body.plate);
    if plate_norm.is_empty() {
        return Err(AppError::BadRequest("`plate` is required".into()));
    }
    let owner_type = body.owner_type.unwrap_or_else(|| "visitor".into());
    if !OWNER_TYPES.contains(&owner_type.as_str()) {
        return Err(AppError::BadRequest(format!(
            "`owner_type` must be one of {OWNER_TYPES:?}"
        )));
    }
    let valid_from = parse_opt_ts(&body.valid_from, "valid_from")?;
    let valid_until = parse_opt_ts(&body.valid_until, "valid_until")?;
    if let (Some(f), Some(u)) = (valid_from, valid_until) {
        if u < f {
            return Err(AppError::BadRequest(
                "`valid_until` must not precede `valid_from`".into(),
            ));
        }
    }
    let id = format!("veh_{}", Uuid::new_v4().simple());
    let now = Utc::now();
    sqlx::query(
        "INSERT INTO vehicles
           (id, plate, plate_norm, owner_name, owner_type, owner_ref, site_id, vehicle_type,
            make, model, color, notes, active, valid_from, valid_until, created_at, updated_at)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
    )
    .bind(&id)
    .bind(body.plate.trim())
    .bind(&plate_norm)
    .bind(&body.owner_name)
    .bind(&owner_type)
    .bind(&body.owner_ref)
    .bind(&body.site_id)
    .bind(&body.vehicle_type)
    .bind(&body.make)
    .bind(&body.model)
    .bind(&body.color)
    .bind(&body.notes)
    .bind(body.active.unwrap_or(true))
    .bind(valid_from)
    .bind(valid_until)
    .bind(now)
    .bind(now)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_vehicle",
        "vehicle",
        &id,
        json!({ "plate": plate_norm }),
    )
    .await;
    let v = sqlx::query_as::<_, Vehicle>("SELECT * FROM vehicles WHERE id = ?")
        .bind(&id)
        .fetch_one(&st.pool)
        .await?;
    Ok((StatusCode::CREATED, Json(v)))
}

async fn update_vehicle(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
    Json(body): Json<VehicleUpdate>,
) -> AppResult<Json<Vehicle>> {
    principal.require(principal.can_manage_registry(), "modify vehicles")?;
    let cur = sqlx::query_as::<_, Vehicle>("SELECT * FROM vehicles WHERE id = ?")
        .bind(&id)
        .fetch_optional(&st.pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("vehicle {id} not found")))?;

    let (plate, plate_norm) = match body.plate {
        Some(p) => {
            let n = normalize_plate(&p);
            if n.is_empty() {
                return Err(AppError::BadRequest("`plate` cannot be empty".into()));
            }
            (p.trim().to_string(), n)
        }
        None => (cur.plate, cur.plate_norm),
    };
    let owner_type = body.owner_type.unwrap_or(cur.owner_type);
    if !OWNER_TYPES.contains(&owner_type.as_str()) {
        return Err(AppError::BadRequest(format!(
            "`owner_type` must be one of {OWNER_TYPES:?}"
        )));
    }
    let valid_from = match &body.valid_from {
        Some(_) => parse_opt_ts(&body.valid_from, "valid_from")?,
        None => cur.valid_from,
    };
    let valid_until = match &body.valid_until {
        Some(_) => parse_opt_ts(&body.valid_until, "valid_until")?,
        None => cur.valid_until,
    };
    if let (Some(f), Some(u)) = (valid_from, valid_until) {
        if u < f {
            return Err(AppError::BadRequest(
                "`valid_until` must not precede `valid_from`".into(),
            ));
        }
    }
    sqlx::query(
        "UPDATE vehicles SET plate=?, plate_norm=?, owner_name=?, owner_type=?, owner_ref=?,
            site_id=?, vehicle_type=?, make=?, model=?, color=?, notes=?, active=?,
            valid_from=?, valid_until=?, updated_at=? WHERE id=?",
    )
    .bind(&plate)
    .bind(&plate_norm)
    .bind(body.owner_name.or(cur.owner_name))
    .bind(&owner_type)
    .bind(body.owner_ref.or(cur.owner_ref))
    .bind(body.site_id.or(cur.site_id))
    .bind(body.vehicle_type.or(cur.vehicle_type))
    .bind(body.make.or(cur.make))
    .bind(body.model.or(cur.model))
    .bind(body.color.or(cur.color))
    .bind(body.notes.or(cur.notes))
    .bind(body.active.unwrap_or(cur.active))
    .bind(valid_from)
    .bind(valid_until)
    .bind(Utc::now())
    .bind(&id)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "update_vehicle",
        "vehicle",
        &id,
        json!({}),
    )
    .await;
    let v = sqlx::query_as::<_, Vehicle>("SELECT * FROM vehicles WHERE id = ?")
        .bind(&id)
        .fetch_one(&st.pool)
        .await?;
    Ok(Json(v))
}

async fn delete_vehicle(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<StatusCode> {
    principal.require(principal.can_manage_registry(), "delete vehicles")?;
    let res = sqlx::query("DELETE FROM vehicles WHERE id = ?")
        .bind(&id)
        .execute(&st.pool)
        .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound(format!("vehicle {id} not found")));
    }
    auth::audit(
        &st.pool,
        &principal,
        "delete_vehicle",
        "vehicle",
        &id,
        json!({}),
    )
    .await;
    Ok(StatusCode::NO_CONTENT)
}

// ---- Visitor passes ------------------------------------------------------

#[derive(Debug, Deserialize)]
struct PassQuery {
    status: Option<String>,
    q: Option<String>,
    limit: Option<i64>,
}

async fn list_passes(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<PassQuery>,
) -> AppResult<Json<Vec<VisitorPass>>> {
    principal.require(principal.can_view(), "view passes")?;
    let limit = q.limit.unwrap_or(200).clamp(1, 2000);
    let like = q.q.as_deref().map(|s| format!("%{}%", s.trim()));
    let rows = sqlx::query_as::<_, VisitorPass>(
        "SELECT * FROM visitor_passes
          WHERE (? IS NULL OR status = ?)
            AND (? IS NULL OR visitor_name LIKE ? OR plate LIKE ? OR code LIKE ? OR host LIKE ?)
          ORDER BY created_at DESC LIMIT ?",
    )
    .bind(&q.status)
    .bind(&q.status)
    .bind(&like)
    .bind(&like)
    .bind(&like)
    .bind(&like)
    .bind(&like)
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(rows))
}

async fn get_pass(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<Json<VisitorPass>> {
    principal.require(principal.can_view(), "view passes")?;
    Ok(Json(load_pass(&st.pool, &id).await?))
}

async fn load_pass(pool: &sqlx::SqlitePool, id: &str) -> AppResult<VisitorPass> {
    sqlx::query_as::<_, VisitorPass>("SELECT * FROM visitor_passes WHERE id = ?")
        .bind(id)
        .fetch_optional(pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("pass {id} not found")))
}

async fn create_pass(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<VisitorPassCreate>,
) -> AppResult<(StatusCode, Json<VisitorPass>)> {
    principal.require(principal.can_operate_gate(), "create visitor passes")?;
    if body.visitor_name.trim().is_empty() {
        return Err(AppError::BadRequest("`visitor_name` is required".into()));
    }
    let now = Utc::now();
    let valid_from = parse_opt_ts(&body.valid_from, "valid_from")?.unwrap_or(now);
    let valid_until = parse_opt_ts(&body.valid_until, "valid_until")?
        .unwrap_or_else(|| now + Duration::hours(24));
    if valid_until < valid_from {
        return Err(AppError::BadRequest(
            "`valid_until` must not precede `valid_from`".into(),
        ));
    }
    let plate_norm = body
        .plate
        .as_deref()
        .map(normalize_plate)
        .filter(|s| !s.is_empty());
    let id = format!("pass_{}", Uuid::new_v4().simple());
    let code = format!(
        "V-{}",
        Uuid::new_v4().simple().to_string()[..6].to_uppercase()
    );
    sqlx::query(
        "INSERT INTO visitor_passes
           (id, code, visitor_name, phone, company, host, purpose, plate, plate_norm, vehicle_desc,
            site_id, valid_from, valid_until, status, created_by, created_at, updated_at)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,'active',?,?,?)",
    )
    .bind(&id)
    .bind(&code)
    .bind(body.visitor_name.trim())
    .bind(&body.phone)
    .bind(&body.company)
    .bind(&body.host)
    .bind(&body.purpose)
    .bind(body.plate.as_deref().map(|p| p.trim().to_string()))
    .bind(&plate_norm)
    .bind(&body.vehicle_desc)
    .bind(&body.site_id)
    .bind(valid_from)
    .bind(valid_until)
    .bind(&principal.id)
    .bind(now)
    .bind(now)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_pass",
        "pass",
        &id,
        json!({ "code": code }),
    )
    .await;
    Ok((StatusCode::CREATED, Json(load_pass(&st.pool, &id).await?)))
}

async fn update_pass(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
    Json(body): Json<VisitorPassUpdate>,
) -> AppResult<Json<VisitorPass>> {
    principal.require(principal.can_operate_gate(), "modify visitor passes")?;
    let cur = load_pass(&st.pool, &id).await?;
    let status = body.status.unwrap_or_else(|| cur.status.clone());
    if !["active", "checked_in", "checked_out", "expired", "revoked"].contains(&status.as_str()) {
        return Err(AppError::BadRequest(
            "`status` must be active|checked_in|checked_out|expired|revoked".into(),
        ));
    }
    // `revoked` is a terminal state: only a manager+ may reinstate it (a guard cannot resurrect a
    // revoked pass by editing its status).
    if cur.status == "revoked" && status != "revoked" {
        principal.require(principal.can_manage_registry(), "reinstate a revoked pass")?;
    }
    let valid_from = match &body.valid_from {
        Some(_) => parse_opt_ts(&body.valid_from, "valid_from")?.unwrap_or(cur.valid_from),
        None => cur.valid_from,
    };
    let valid_until = match &body.valid_until {
        Some(_) => parse_opt_ts(&body.valid_until, "valid_until")?.unwrap_or(cur.valid_until),
        None => cur.valid_until,
    };
    if valid_until < valid_from {
        return Err(AppError::BadRequest(
            "`valid_until` must not precede `valid_from`".into(),
        ));
    }
    let (plate, plate_norm) = match body.plate {
        Some(p) => {
            let n = normalize_plate(&p);
            (Some(p.trim().to_string()), (!n.is_empty()).then_some(n))
        }
        None => (cur.plate, cur.plate_norm),
    };
    sqlx::query(
        "UPDATE visitor_passes SET visitor_name=?, phone=?, company=?, host=?, purpose=?, plate=?,
            plate_norm=?, vehicle_desc=?, valid_from=?, valid_until=?, status=?, updated_at=? WHERE id=?",
    )
    .bind(body.visitor_name.unwrap_or(cur.visitor_name))
    .bind(body.phone.or(cur.phone))
    .bind(body.company.or(cur.company))
    .bind(body.host.or(cur.host))
    .bind(body.purpose.or(cur.purpose))
    .bind(&plate)
    .bind(&plate_norm)
    .bind(body.vehicle_desc.or(cur.vehicle_desc))
    .bind(valid_from)
    .bind(valid_until)
    .bind(&status)
    .bind(Utc::now())
    .bind(&id)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "update_pass",
        "pass",
        &id,
        json!({ "status": status }),
    )
    .await;
    Ok(Json(load_pass(&st.pool, &id).await?))
}

async fn delete_pass(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<StatusCode> {
    principal.require(principal.can_manage_registry(), "delete visitor passes")?;
    let res = sqlx::query("DELETE FROM visitor_passes WHERE id = ?")
        .bind(&id)
        .execute(&st.pool)
        .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound(format!("pass {id} not found")));
    }
    auth::audit(&st.pool, &principal, "delete_pass", "pass", &id, json!({})).await;
    Ok(StatusCode::NO_CONTENT)
}

async fn checkin_pass(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<Json<VisitorPass>> {
    principal.require(principal.can_operate_gate(), "check in visitors")?;
    let pass = load_pass(&st.pool, &id).await?;
    // Only an active (or already-checked-in, idempotent) pass can be checked in. revoked / expired /
    // checked_out are terminal-ish and must not be silently reactivated.
    if !matches!(pass.status.as_str(), "active" | "checked_in") {
        return Err(AppError::BadRequest(format!(
            "pass is {} and cannot be checked in",
            pass.status
        )));
    }
    let now = Utc::now();
    sqlx::query(
        "UPDATE visitor_passes SET status='checked_in', checked_in_at=?, updated_at=? WHERE id=?",
    )
    .bind(now)
    .bind(now)
    .bind(&id)
    .execute(&st.pool)
    .await?;
    record_manual_entry(&st, &principal, &pass, "visitor_checkin", "inbound", now).await;
    auth::audit(&st.pool, &principal, "checkin_pass", "pass", &id, json!({})).await;
    Ok(Json(load_pass(&st.pool, &id).await?))
}

async fn checkout_pass(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<Json<VisitorPass>> {
    principal.require(principal.can_operate_gate(), "check out visitors")?;
    let pass = load_pass(&st.pool, &id).await?;
    // A revoked / expired pass is terminal — do not flip it to checked_out (which would also let it
    // be resurrected via a later check-in).
    if matches!(pass.status.as_str(), "revoked" | "expired") {
        return Err(AppError::BadRequest(format!(
            "pass is {} and cannot be checked out",
            pass.status
        )));
    }
    let now = Utc::now();
    sqlx::query(
        "UPDATE visitor_passes SET status='checked_out', checked_out_at=?, updated_at=? WHERE id=?",
    )
    .bind(now)
    .bind(now)
    .bind(&id)
    .execute(&st.pool)
    .await?;
    record_manual_entry(&st, &principal, &pass, "visitor_checkout", "outbound", now).await;
    auth::audit(
        &st.pool,
        &principal,
        "checkout_pass",
        "pass",
        &id,
        json!({}),
    )
    .await;
    Ok(Json(load_pass(&st.pool, &id).await?))
}

/// Write a guard-initiated entry event (manual check-in/out) into the canonical feed.
async fn record_manual_entry(
    st: &AppState,
    principal: &Principal,
    pass: &VisitorPass,
    event_type: &str,
    direction: &str,
    now: DateTime<Utc>,
) {
    let id = format!("evt_{}", Uuid::new_v4().simple());
    let subject = json!({
        "type": "visitor",
        "visitor_name": pass.visitor_name,
        "plate": pass.plate,
        "pass_code": pass.code,
    });
    let authorization =
        json!({ "status": "matched", "source": "visitor_pass", "pass_id": pass.id });
    let workflow = json!({ "status": "confirmed", "resolved_by": principal.name });
    let audit_j = json!({ "created_by": principal.id });
    let _ = sqlx::query(
        "INSERT INTO entry_events
           (id, site_id, camera_id, event_type, timestamp, direction, plate, plate_confidence,
            subject, authorization, auth_status, evidence, workflow_status, workflow, audit,
            track_id, created_at)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
    )
    .bind(&id)
    .bind(&pass.site_id)
    .bind(Option::<String>::None)
    .bind(event_type)
    .bind(now)
    .bind(direction)
    .bind(&pass.plate_norm)
    .bind(Option::<f64>::None)
    .bind(SqlxJson(&subject))
    .bind(SqlxJson(&authorization))
    .bind("matched")
    .bind(SqlxJson(json!({})))
    .bind("confirmed")
    .bind(SqlxJson(&workflow))
    .bind(SqlxJson(&audit_j))
    .bind(Option::<String>::None)
    .bind(now)
    .execute(&st.pool)
    .await;
}

// ---- Watchlist -----------------------------------------------------------

async fn list_watchlist(
    State(st): State<AppState>,
    principal: Principal,
) -> AppResult<Json<Vec<Watchlist>>> {
    principal.require(principal.can_view(), "view watchlist")?;
    // Bound the result set: the watchlist can grow large, and an unbounded SELECT * would load every
    // row into memory at once (OOM/latency risk). 1000 is well above any realistic operator view.
    let rows = sqlx::query_as::<_, Watchlist>(
        "SELECT * FROM watchlist ORDER BY created_at DESC LIMIT 1000",
    )
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(rows))
}

async fn create_watch(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<WatchlistCreate>,
) -> AppResult<(StatusCode, Json<Watchlist>)> {
    principal.require(principal.can_manage_registry(), "manage the watchlist")?;
    let plate_norm = normalize_plate(&body.plate);
    if plate_norm.is_empty() {
        return Err(AppError::BadRequest("`plate` is required".into()));
    }
    let kind = body.kind.unwrap_or_else(|| "block".into());
    if !WATCH_KINDS.contains(&kind.as_str()) {
        return Err(AppError::BadRequest(format!(
            "`kind` must be one of {WATCH_KINDS:?}"
        )));
    }
    let severity = body.severity.unwrap_or_else(|| "warning".into());
    if !SEVERITIES.contains(&severity.as_str()) {
        return Err(AppError::BadRequest(format!(
            "`severity` must be one of {SEVERITIES:?}"
        )));
    }
    let id = format!("wl_{}", Uuid::new_v4().simple());
    let now = Utc::now();
    sqlx::query(
        "INSERT INTO watchlist (id, plate, plate_norm, kind, reason, severity, active, created_by, created_at, updated_at)
         VALUES (?,?,?,?,?,?,?,?,?,?)",
    )
    .bind(&id)
    .bind(body.plate.trim())
    .bind(&plate_norm)
    .bind(&kind)
    .bind(&body.reason)
    .bind(&severity)
    .bind(body.active.unwrap_or(true))
    .bind(&principal.id)
    .bind(now)
    .bind(now)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_watchlist",
        "watchlist",
        &id,
        json!({ "plate": plate_norm, "kind": kind }),
    )
    .await;
    let w = sqlx::query_as::<_, Watchlist>("SELECT * FROM watchlist WHERE id = ?")
        .bind(&id)
        .fetch_one(&st.pool)
        .await?;
    Ok((StatusCode::CREATED, Json(w)))
}

async fn update_watch(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
    Json(body): Json<WatchlistUpdate>,
) -> AppResult<Json<Watchlist>> {
    principal.require(principal.can_manage_registry(), "manage the watchlist")?;
    let cur = sqlx::query_as::<_, Watchlist>("SELECT * FROM watchlist WHERE id = ?")
        .bind(&id)
        .fetch_optional(&st.pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("watchlist entry {id} not found")))?;
    let kind = body.kind.unwrap_or(cur.kind);
    if !WATCH_KINDS.contains(&kind.as_str()) {
        return Err(AppError::BadRequest(format!(
            "`kind` must be one of {WATCH_KINDS:?}"
        )));
    }
    let severity = body.severity.unwrap_or(cur.severity);
    if !SEVERITIES.contains(&severity.as_str()) {
        return Err(AppError::BadRequest(format!(
            "`severity` must be one of {SEVERITIES:?}"
        )));
    }
    sqlx::query(
        "UPDATE watchlist SET kind=?, reason=?, severity=?, active=?, updated_at=? WHERE id=?",
    )
    .bind(&kind)
    .bind(body.reason.or(cur.reason))
    .bind(&severity)
    .bind(body.active.unwrap_or(cur.active))
    .bind(Utc::now())
    .bind(&id)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "update_watchlist",
        "watchlist",
        &id,
        json!({}),
    )
    .await;
    let w = sqlx::query_as::<_, Watchlist>("SELECT * FROM watchlist WHERE id = ?")
        .bind(&id)
        .fetch_one(&st.pool)
        .await?;
    Ok(Json(w))
}

async fn delete_watch(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<StatusCode> {
    principal.require(principal.can_manage_registry(), "manage the watchlist")?;
    let res = sqlx::query("DELETE FROM watchlist WHERE id = ?")
        .bind(&id)
        .execute(&st.pool)
        .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound(format!(
            "watchlist entry {id} not found"
        )));
    }
    auth::audit(
        &st.pool,
        &principal,
        "delete_watchlist",
        "watchlist",
        &id,
        json!({}),
    )
    .await;
    Ok(StatusCode::NO_CONTENT)
}

// ---- Entry events + guard workflow --------------------------------------

#[derive(Debug, Deserialize)]
struct EntryEventQuery {
    from: Option<String>,
    to: Option<String>,
    plate: Option<String>,
    auth_status: Option<String>,
    workflow_status: Option<String>,
    event_type: Option<String>,
    limit: Option<i64>,
}

async fn list_entry_events(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<EntryEventQuery>,
) -> AppResult<Json<Vec<EntryEvent>>> {
    principal.require(principal.can_view(), "view entry events")?;
    let limit = q.limit.unwrap_or(200).clamp(1, 5000);
    let from = parse_opt_ts(&q.from, "from")?;
    let to = parse_opt_ts(&q.to, "to")?;
    let plate_norm = q.plate.as_deref().map(normalize_plate);
    let rows = sqlx::query_as::<_, EntryEvent>(
        "SELECT * FROM entry_events
          WHERE (? IS NULL OR timestamp >= ?)
            AND (? IS NULL OR timestamp <= ?)
            AND (? IS NULL OR plate = ?)
            AND (? IS NULL OR auth_status = ?)
            AND (? IS NULL OR workflow_status = ?)
            AND (? IS NULL OR event_type = ?)
          ORDER BY timestamp DESC LIMIT ?",
    )
    .bind(from)
    .bind(from)
    .bind(to)
    .bind(to)
    .bind(&plate_norm)
    .bind(&plate_norm)
    .bind(&q.auth_status)
    .bind(&q.auth_status)
    .bind(&q.workflow_status)
    .bind(&q.workflow_status)
    .bind(&q.event_type)
    .bind(&q.event_type)
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(rows))
}

async fn get_entry_event(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<Json<EntryEvent>> {
    principal.require(principal.can_view(), "view entry events")?;
    let ev = sqlx::query_as::<_, EntryEvent>("SELECT * FROM entry_events WHERE id = ?")
        .bind(&id)
        .fetch_optional(&st.pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("entry event {id} not found")))?;
    Ok(Json(ev))
}

#[derive(Debug, Deserialize, Default)]
struct ResolveBody {
    note: Option<String>,
}

async fn confirm_event(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
    body: Option<Json<ResolveBody>>,
) -> AppResult<Json<EntryEvent>> {
    resolve_event(
        st,
        principal,
        id,
        "confirmed",
        body.map(|b| b.0).unwrap_or_default(),
    )
    .await
}

async fn reject_event(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
    body: Option<Json<ResolveBody>>,
) -> AppResult<Json<EntryEvent>> {
    resolve_event(
        st,
        principal,
        id,
        "rejected",
        body.map(|b| b.0).unwrap_or_default(),
    )
    .await
}

async fn resolve_event(
    st: AppState,
    principal: Principal,
    id: String,
    status: &str,
    body: ResolveBody,
) -> AppResult<Json<EntryEvent>> {
    principal.require(principal.can_operate_gate(), "resolve entry events")?;
    let ev = sqlx::query_as::<_, EntryEvent>("SELECT * FROM entry_events WHERE id = ?")
        .bind(&id)
        .fetch_optional(&st.pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("entry event {id} not found")))?;
    let now = Utc::now();
    let mut workflow = ev.workflow.0.clone();
    if let Some(obj) = workflow.as_object_mut() {
        obj.insert("status".into(), json!(status));
        obj.insert("resolved_by".into(), json!(principal.name));
        obj.insert("resolved_by_id".into(), json!(principal.id));
        obj.insert("resolved_at".into(), json!(now.to_rfc3339()));
        if let Some(note) = &body.note {
            obj.insert("note".into(), json!(note));
        }
    }
    sqlx::query("UPDATE entry_events SET workflow_status=?, workflow=? WHERE id=?")
        .bind(status)
        .bind(SqlxJson(&workflow))
        .bind(&id)
        .execute(&st.pool)
        .await?;
    auth::audit(
        &st.pool,
        &principal,
        &format!("entry_{status}"),
        "entry_event",
        &id,
        json!({ "plate": ev.plate, "note": body.note }),
    )
    .await;
    let ev = sqlx::query_as::<_, EntryEvent>("SELECT * FROM entry_events WHERE id = ?")
        .bind(&id)
        .fetch_one(&st.pool)
        .await?;
    Ok(Json(ev))
}

// ---- Reports -------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct ReportQuery {
    date: Option<String>,
    from: Option<String>,
    to: Option<String>,
    limit: Option<i64>,
}

/// Resolve a [from, to) window from either an explicit from/to or a `date=YYYY-MM-DD` (UTC day).
fn report_window(q: &ReportQuery) -> AppResult<(DateTime<Utc>, DateTime<Utc>)> {
    if q.from.is_some() || q.to.is_some() {
        let from = parse_opt_ts(&q.from, "from")?.unwrap_or_else(|| Utc::now() - Duration::days(1));
        let to = parse_opt_ts(&q.to, "to")?.unwrap_or_else(Utc::now);
        if to < from {
            return Err(AppError::BadRequest("`to` must not precede `from`".into()));
        }
        return Ok((from, to));
    }
    let day = match &q.date {
        Some(d) => chrono::NaiveDate::parse_from_str(d.trim(), "%Y-%m-%d")
            .map_err(|_| AppError::BadRequest("`date` must be YYYY-MM-DD".into()))?,
        None => Utc::now().date_naive(),
    };
    let start = day
        .and_hms_opt(0, 0, 0)
        .ok_or_else(|| AppError::BadRequest("invalid date".into()))?
        .and_utc();
    Ok((start, start + Duration::days(1)))
}

async fn report_entry_log(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<ReportQuery>,
) -> AppResult<Json<Value>> {
    principal.require(principal.can_view(), "view reports")?;
    let (from, to) = report_window(&q)?;
    let limit = q.limit.unwrap_or(1000).clamp(1, 10000);
    let events = sqlx::query_as::<_, EntryEvent>(
        "SELECT * FROM entry_events WHERE timestamp >= ? AND timestamp < ? ORDER BY timestamp DESC LIMIT ?",
    )
    .bind(from)
    .bind(to)
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    let counts = auth_status_counts(&st.pool, from, to).await?;
    Ok(Json(json!({
        "from": from, "to": to,
        "total": events.len(),
        "by_auth_status": counts,
        "events": events,
    })))
}

async fn report_exceptions(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<ReportQuery>,
) -> AppResult<Json<Value>> {
    principal.require(principal.can_view(), "view reports")?;
    let (from, to) = report_window(&q)?;
    let limit = q.limit.unwrap_or(1000).clamp(1, 10000);
    // Exceptions = anything that is not an automatic clean match: blocked / exception / unmatched,
    // plus any event a guard explicitly rejected.
    let events = sqlx::query_as::<_, EntryEvent>(
        "SELECT * FROM entry_events
          WHERE timestamp >= ? AND timestamp < ?
            AND (auth_status IN ('blocked','exception','unmatched') OR workflow_status = 'rejected')
          ORDER BY timestamp DESC LIMIT ?",
    )
    .bind(from)
    .bind(to)
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(json!({
        "from": from, "to": to,
        "total": events.len(),
        "events": events,
    })))
}

async fn auth_status_counts(
    pool: &sqlx::SqlitePool,
    from: DateTime<Utc>,
    to: DateTime<Utc>,
) -> AppResult<Value> {
    let rows: Vec<(String, i64)> = sqlx::query_as(
        "SELECT auth_status, COUNT(*) FROM entry_events
          WHERE timestamp >= ? AND timestamp < ? GROUP BY auth_status",
    )
    .bind(from)
    .bind(to)
    .fetch_all(pool)
    .await?;
    let mut map = serde_json::Map::new();
    for (k, v) in rows {
        map.insert(k, json!(v));
    }
    Ok(Value::Object(map))
}

#[derive(Debug, Deserialize)]
struct AuditQuery {
    from: Option<String>,
    to: Option<String>,
    actor: Option<String>,
    action: Option<String>,
    limit: Option<i64>,
}

async fn list_audit(
    State(st): State<AppState>,
    principal: Principal,
    Query(q): Query<AuditQuery>,
) -> AppResult<Json<Vec<AuditLog>>> {
    // The audit log records who did what — restricted to manager+ (it can reveal operator activity).
    principal.require(principal.can_manage_registry(), "view the audit log")?;
    let limit = q.limit.unwrap_or(200).clamp(1, 5000);
    let from = parse_opt_ts(&q.from, "from")?;
    let to = parse_opt_ts(&q.to, "to")?;
    let rows = sqlx::query_as::<_, AuditLog>(
        "SELECT * FROM audit_log
          WHERE (? IS NULL OR created_at >= ?)
            AND (? IS NULL OR created_at <= ?)
            AND (? IS NULL OR actor = ?)
            AND (? IS NULL OR action = ?)
          ORDER BY created_at DESC LIMIT ?",
    )
    .bind(from)
    .bind(from)
    .bind(to)
    .bind(to)
    .bind(&q.actor)
    .bind(&q.actor)
    .bind(&q.action)
    .bind(&q.action)
    .bind(limit)
    .fetch_all(&st.pool)
    .await?;
    Ok(Json(rows))
}