beads_rust 0.1.45

Agent-first issue tracker (SQLite + JSONL)
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
//! Event storage operations for `beads_rust`.
//!
//! This module implements the audit event system with:
//! - Event insertion (atomic with mutations)
//! - Event retrieval (newest first, DESC ordering)
//! - Schema definitions for the events table
//!
//! Events are local DB only - never exported to JSONL.

use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use fsqlite::{Connection, Row};
use fsqlite_types::SqliteValue;

use crate::error::{BeadsError, Result};
use crate::model::{Event, EventType};

/// SQL schema for the events table.
///
/// This schema matches the classic bd `events` table structure.
pub const EVENTS_TABLE_SCHEMA: &str = r"
CREATE TABLE IF NOT EXISTS events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    issue_id TEXT NOT NULL,
    event_type TEXT NOT NULL,
    actor TEXT NOT NULL DEFAULT '',
    old_value TEXT,
    new_value TEXT,
    comment TEXT,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (issue_id) REFERENCES issues(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_events_issue ON events(issue_id);
CREATE INDEX IF NOT EXISTS idx_events_created_at ON events(created_at);
CREATE INDEX IF NOT EXISTS idx_events_event_type ON events(event_type);
CREATE INDEX IF NOT EXISTS idx_events_actor ON events(actor);
";

/// Insert an event within a transaction.
///
/// This function should be called within the same transaction (BEGIN/COMMIT)
/// as the mutation that triggered the event. The caller is responsible for
/// managing the transaction boundaries on the connection.
///
/// # Arguments
///
/// * `conn` - Database connection (with an active transaction)
/// * `issue_id` - ID of the issue the event pertains to
/// * `event_type` - Type of event being recorded
/// * `actor` - Username or identifier of the person/agent making the change
/// * `old_value` - Previous value (for changes)
/// * `new_value` - New value (for changes)
/// * `comment` - Optional comment text (for commented events)
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_event(
    conn: &Connection,
    issue_id: &str,
    event_type: &EventType,
    actor: &str,
    old_value: Option<&str>,
    new_value: Option<&str>,
    comment: Option<&str>,
) -> Result<i64> {
    let now = Utc::now();
    conn.execute_with_params(
        r"
        INSERT INTO events (issue_id, event_type, actor, old_value, new_value, comment, created_at)
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
        ",
        &[
            SqliteValue::from(issue_id),
            SqliteValue::from(event_type.as_str()),
            SqliteValue::from(actor),
            old_value.map_or(SqliteValue::Null, SqliteValue::from),
            new_value.map_or(SqliteValue::Null, SqliteValue::from),
            comment.map_or(SqliteValue::Null, SqliteValue::from),
            SqliteValue::from(now.to_rfc3339()),
        ],
    )?;

    let row = conn.query_row("SELECT last_insert_rowid()")?;
    let id = row.get(0).and_then(SqliteValue::as_integer).unwrap_or(0);
    Ok(id)
}

/// Insert a "created" event for a new issue.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_created_event(conn: &Connection, issue_id: &str, actor: &str) -> Result<i64> {
    insert_event(conn, issue_id, &EventType::Created, actor, None, None, None)
}

/// Insert an "updated" event for a field change.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_updated_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    field: &str,
    old_value: Option<&str>,
    new_value: Option<&str>,
) -> Result<i64> {
    let comment = Some(format!("Updated field: {field}"));
    insert_event(
        conn,
        issue_id,
        &EventType::Updated,
        actor,
        old_value,
        new_value,
        comment.as_deref(),
    )
}

/// Insert a `status_changed` event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_status_changed_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    old_status: &str,
    new_status: &str,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::StatusChanged,
        actor,
        Some(old_status),
        Some(new_status),
        None,
    )
}

/// Insert a "closed" event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_closed_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    close_reason: Option<&str>,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::Closed,
        actor,
        None,
        None,
        close_reason,
    )
}

/// Insert a "reopened" event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_reopened_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    reason: Option<&str>,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::Reopened,
        actor,
        None,
        None,
        reason,
    )
}

/// Insert a "commented" event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_commented_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    comment_text: &str,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::Commented,
        actor,
        None,
        None,
        Some(comment_text),
    )
}

/// Insert a `dependency_added` event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_dependency_added_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    dep_type: &str,
    depends_on_id: &str,
) -> Result<i64> {
    let comment = format!("Added dependency on {depends_on_id} ({dep_type})");
    insert_event(
        conn,
        issue_id,
        &EventType::DependencyAdded,
        actor,
        None,
        Some(depends_on_id),
        Some(&comment),
    )
}

/// Insert a `dependency_removed` event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_dependency_removed_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    depends_on_id: &str,
) -> Result<i64> {
    let comment = format!("Removed dependency on {depends_on_id}");
    insert_event(
        conn,
        issue_id,
        &EventType::DependencyRemoved,
        actor,
        Some(depends_on_id),
        None,
        Some(&comment),
    )
}

/// Insert a `label_added` event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_label_added_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    label: &str,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::LabelAdded,
        actor,
        None,
        Some(label),
        None,
    )
}

/// Insert a `label_removed` event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_label_removed_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    label: &str,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::LabelRemoved,
        actor,
        Some(label),
        None,
        None,
    )
}

/// Insert a "deleted" (tombstone) event.
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_deleted_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    delete_reason: Option<&str>,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::Deleted,
        actor,
        None,
        None,
        delete_reason,
    )
}

/// Insert a "restored" event (if restore is supported).
///
/// # Errors
///
/// Returns an error if the database insert fails.
pub fn insert_restored_event(
    conn: &Connection,
    issue_id: &str,
    actor: &str,
    reason: Option<&str>,
) -> Result<i64> {
    insert_event(
        conn,
        issue_id,
        &EventType::Restored,
        actor,
        None,
        None,
        reason,
    )
}

/// Get events for an issue, ordered by `created_at` DESC (newest first).
///
/// # Arguments
///
/// * `conn` - Database connection
/// * `issue_id` - ID of the issue to get events for
/// * `limit` - Maximum number of events to return (0 = no limit)
///
/// # Errors
///
/// Returns an error if the database query fails.
pub fn get_events(conn: &Connection, issue_id: &str, limit: usize) -> Result<Vec<Event>> {
    let events = conn.query_with_params(
        &format!(
            r"
            SELECT id, issue_id, event_type, actor, old_value, new_value, comment, created_at
            FROM events
            WHERE issue_id = ?1
            ORDER BY created_at DESC, id DESC
            {}
            ",
            if limit > 0 {
                format!("LIMIT {limit}")
            } else {
                String::new()
            }
        ),
        &[SqliteValue::from(issue_id)],
    )?;

    let mut result: Vec<Event> = events.iter().map(event_from_row).collect::<Result<_>>()?;
    // fsqlite may not honour ORDER BY DESC or LIMIT in all query plans;
    // enforce both in Rust for correctness.
    result.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(b.id.cmp(&a.id)));
    if limit > 0 && result.len() > limit {
        result.truncate(limit);
    }
    Ok(result)
}

fn event_from_row(row: &Row) -> Result<Event> {
    let id = row
        .get(0)
        .and_then(SqliteValue::as_integer)
        .ok_or_else(|| BeadsError::Config("events row missing id".to_string()))?;
    let issue_id = row
        .get(1)
        .and_then(|v| v.as_text())
        .ok_or_else(|| BeadsError::Config("events row missing issue_id".to_string()))?
        .to_string();
    let event_type_str = row.get(2).and_then(|v| v.as_text()).ok_or_else(|| {
        BeadsError::Config(format!("events row missing event_type for {issue_id}"))
    })?;
    let actor = row
        .get(3)
        .and_then(|v| v.as_text())
        .ok_or_else(|| BeadsError::Config(format!("events row missing actor for {issue_id}")))?;
    let actor = actor.to_string();
    let old_value = row.get(4).and_then(|v| v.as_text()).map(String::from);
    let new_value = row.get(5).and_then(|v| v.as_text()).map(String::from);
    let comment = row.get(6).and_then(|v| v.as_text()).map(String::from);
    let created_at_str = row.get(7).and_then(|v| v.as_text()).ok_or_else(|| {
        BeadsError::Config(format!("events row missing created_at for {issue_id}"))
    })?;

    // Parse event type
    let event_type = parse_event_type(event_type_str);

    // Parse timestamp (support RFC3339 and SQLite default format)
    let created_at = parse_event_timestamp(created_at_str)?;

    Ok(Event {
        id,
        issue_id,
        event_type,
        actor,
        old_value,
        new_value,
        comment,
        created_at,
    })
}

fn parse_event_timestamp(value: &str) -> Result<DateTime<Utc>> {
    if let Ok(dt) = DateTime::parse_from_rfc3339(value) {
        return Ok(dt.with_timezone(&Utc));
    }

    if let Ok(naive) = NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S") {
        return Ok(Utc.from_utc_datetime(&naive));
    }

    Err(BeadsError::Config(format!(
        "Invalid event timestamp: {value}"
    )))
}

/// Get all events across all issues, ordered by `created_at` DESC.
///
/// Useful for audit trails and debugging.
///
/// # Errors
///
/// Returns an error if the database query fails.
pub fn get_all_events(conn: &Connection, limit: usize) -> Result<Vec<Event>> {
    let rows = conn.query(&format!(
        r"
            SELECT id, issue_id, event_type, actor, old_value, new_value, comment, created_at
            FROM events
            ORDER BY created_at DESC, id DESC
            {}
            ",
        if limit > 0 {
            format!("LIMIT {limit}")
        } else {
            String::new()
        }
    ))?;

    let mut result: Vec<Event> = rows.iter().map(event_from_row).collect::<Result<_>>()?;
    // fsqlite may not honour ORDER BY DESC or LIMIT in all query plans;
    // enforce both in Rust for correctness.
    result.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(b.id.cmp(&a.id)));
    if limit > 0 && result.len() > limit {
        result.truncate(limit);
    }
    Ok(result)
}

/// Get event count for an issue.
///
/// # Errors
///
/// Returns an error if the database query fails.
pub fn count_events(conn: &Connection, issue_id: &str) -> Result<i64> {
    let row = conn.query_row_with_params(
        "SELECT COUNT(*) FROM events WHERE issue_id = ?1",
        &[SqliteValue::from(issue_id)],
    )?;
    let count = row.get(0).and_then(SqliteValue::as_integer).unwrap_or(0);
    Ok(count)
}

/// Parse event type string to `EventType` enum.
fn parse_event_type(s: &str) -> EventType {
    match s {
        "created" => EventType::Created,
        "updated" => EventType::Updated,
        "status_changed" => EventType::StatusChanged,
        "priority_changed" => EventType::PriorityChanged,
        "assignee_changed" => EventType::AssigneeChanged,
        "commented" => EventType::Commented,
        "closed" => EventType::Closed,
        "reopened" => EventType::Reopened,
        "dependency_added" => EventType::DependencyAdded,
        "dependency_removed" => EventType::DependencyRemoved,
        "label_added" => EventType::LabelAdded,
        "label_removed" => EventType::LabelRemoved,
        "compacted" => EventType::Compacted,
        "deleted" => EventType::Deleted,
        "restored" => EventType::Restored,
        other => EventType::Custom(other.to_string()),
    }
}

/// Initialize the events table in the database.
///
/// # Errors
///
/// Returns an error if table creation fails.
pub fn init_events_table(conn: &Connection) -> Result<()> {
    super::schema::execute_batch(conn, EVENTS_TABLE_SCHEMA)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::schema::execute_batch;
    use fsqlite::Connection;

    fn setup_test_db() -> Connection {
        let conn = Connection::open(":memory:").expect("Failed to create in-memory database");

        // Create minimal issues table for foreign key
        execute_batch(
            &conn,
            r"
            CREATE TABLE issues (
                id TEXT PRIMARY KEY,
                title TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'open'
            );
            ",
        )
        .expect("Failed to create issues table");

        // Create events table
        init_events_table(&conn).expect("Failed to create events table");

        // Insert a test issue
        conn.execute("INSERT INTO issues (id, title) VALUES ('test-001', 'Test Issue')")
            .expect("Failed to insert test issue");

        conn
    }

    #[test]
    fn test_insert_created_event() {
        let conn = setup_test_db();
        conn.execute("BEGIN").expect("Failed to start tx");

        let id = insert_created_event(&conn, "test-001", "alice").expect("Failed to insert event");
        conn.execute("COMMIT").expect("Failed to commit");

        assert!(id > 0);

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::Created);
        assert_eq!(events[0].actor, "alice");
    }

    #[test]
    fn test_insert_status_changed_event() {
        let conn = setup_test_db();
        conn.execute("BEGIN").expect("Failed to start tx");

        insert_status_changed_event(&conn, "test-001", "bob", "open", "in_progress")
            .expect("Failed to insert event");
        conn.execute("COMMIT").expect("Failed to commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::StatusChanged);
        assert_eq!(events[0].old_value.as_deref(), Some("open"));
        assert_eq!(events[0].new_value.as_deref(), Some("in_progress"));
    }

    #[test]
    fn test_insert_closed_event() {
        let conn = setup_test_db();
        conn.execute("BEGIN").expect("Failed to start tx");

        insert_closed_event(&conn, "test-001", "carol", Some("Completed the work"))
            .expect("Failed to insert event");
        conn.execute("COMMIT").expect("Failed to commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::Closed);
        assert_eq!(events[0].comment.as_deref(), Some("Completed the work"));
    }

    #[test]
    fn test_insert_commented_event() {
        let conn = setup_test_db();
        conn.execute("BEGIN").expect("Failed to start tx");

        insert_commented_event(&conn, "test-001", "dave", "This is a comment")
            .expect("Failed to insert event");
        conn.execute("COMMIT").expect("Failed to commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::Commented);
        assert_eq!(events[0].comment.as_deref(), Some("This is a comment"));
    }

    #[test]
    fn test_insert_dependency_added_event() {
        let conn = setup_test_db();

        // Add second issue for dependency
        conn.execute("INSERT INTO issues (id, title) VALUES ('test-002', 'Blocking Issue')")
            .expect("Failed to insert second issue");

        conn.execute("BEGIN").expect("Failed to start tx");
        insert_dependency_added_event(&conn, "test-001", "eve", "blocks", "test-002")
            .expect("Failed to insert event");
        conn.execute("COMMIT").expect("Failed to commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::DependencyAdded);
        assert_eq!(events[0].new_value.as_deref(), Some("test-002"));
        assert!(events[0].comment.as_ref().unwrap().contains("blocks"));
    }

    #[test]
    fn test_insert_label_events() {
        let conn = setup_test_db();
        conn.execute("BEGIN").expect("Failed to start tx");

        insert_label_added_event(&conn, "test-001", "frank", "urgent")
            .expect("Failed to insert label added event");
        insert_label_removed_event(&conn, "test-001", "frank", "urgent")
            .expect("Failed to insert label removed event");
        conn.execute("COMMIT").expect("Failed to commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 2);

        // Events are DESC order, so removed is first
        assert_eq!(events[0].event_type, EventType::LabelRemoved);
        assert_eq!(events[0].old_value.as_deref(), Some("urgent"));

        assert_eq!(events[1].event_type, EventType::LabelAdded);
        assert_eq!(events[1].new_value.as_deref(), Some("urgent"));
    }

    #[test]
    fn test_get_events_ordering() {
        let conn = setup_test_db();

        // Insert multiple events
        for i in 0..5 {
            conn.execute("BEGIN").expect("Failed to start tx");
            insert_commented_event(&conn, "test-001", "user", &format!("Comment {i}"))
                .expect("Failed to insert event");
            conn.execute("COMMIT").expect("Failed to commit");
        }

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 5);

        // Verify DESC ordering (newest first)
        assert!(events[0].comment.as_ref().unwrap().contains("Comment 4"));
        assert!(events[4].comment.as_ref().unwrap().contains("Comment 0"));
    }

    #[test]
    fn test_get_events_with_limit() {
        let conn = setup_test_db();

        // Insert 10 events
        for i in 0..10 {
            conn.execute("BEGIN").expect("Failed to start tx");
            insert_commented_event(&conn, "test-001", "user", &format!("Comment {i}"))
                .expect("Failed to insert event");
            conn.execute("COMMIT").expect("Failed to commit");
        }

        // Get only 3 events
        let events = get_events(&conn, "test-001", 3).expect("Failed to get events");
        assert_eq!(events.len(), 3);

        // Should be newest 3
        assert!(events[0].comment.as_ref().unwrap().contains("Comment 9"));
        assert!(events[2].comment.as_ref().unwrap().contains("Comment 7"));
    }

    #[test]
    fn test_count_events() {
        let conn = setup_test_db();

        // Insert events
        for _ in 0..5 {
            conn.execute("BEGIN").expect("Failed to start tx");
            insert_commented_event(&conn, "test-001", "user", "A comment")
                .expect("Failed to insert event");
            conn.execute("COMMIT").expect("Failed to commit");
        }

        let count = count_events(&conn, "test-001").expect("Failed to count events");
        assert_eq!(count, 5);
    }

    #[test]
    fn test_deleted_and_restored_events() {
        let conn = setup_test_db();
        conn.execute("BEGIN").expect("Failed to start tx");

        insert_deleted_event(&conn, "test-001", "admin", Some("Duplicate issue"))
            .expect("Failed to insert deleted event");
        insert_restored_event(&conn, "test-001", "admin", Some("Not a duplicate"))
            .expect("Failed to insert restored event");
        conn.execute("COMMIT").expect("Failed to commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 2);

        // Restored is newer (first in DESC order)
        assert_eq!(events[0].event_type, EventType::Restored);
        assert_eq!(events[0].comment.as_deref(), Some("Not a duplicate"));

        assert_eq!(events[1].event_type, EventType::Deleted);
        assert_eq!(events[1].comment.as_deref(), Some("Duplicate issue"));
    }

    #[test]
    fn test_reopened_event() {
        let conn = setup_test_db();
        conn.execute("BEGIN").expect("Failed to start tx");

        insert_reopened_event(&conn, "test-001", "manager", Some("Need more work"))
            .expect("Failed to insert reopened event");
        conn.execute("COMMIT").expect("Failed to commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::Reopened);
        assert_eq!(events[0].comment.as_deref(), Some("Need more work"));
    }

    #[test]
    fn test_get_all_events() {
        let conn = setup_test_db();

        // Add second issue
        conn.execute("INSERT INTO issues (id, title) VALUES ('test-002', 'Second Issue')")
            .expect("Failed to insert second issue");

        // Insert events for both issues
        conn.execute("BEGIN").expect("Failed to start tx");
        insert_created_event(&conn, "test-001", "alice").expect("Failed to insert event");
        insert_created_event(&conn, "test-002", "bob").expect("Failed to insert event");
        conn.execute("COMMIT").expect("Failed to commit");

        let all_events = get_all_events(&conn, 0).expect("Failed to get all events");
        assert_eq!(all_events.len(), 2);
    }

    #[test]
    fn test_multiple_event_types_sequence() {
        let conn = setup_test_db();

        // Simulate a typical issue lifecycle
        conn.execute("BEGIN").expect("Failed to start tx");
        insert_created_event(&conn, "test-001", "alice").expect("Created");
        conn.execute("COMMIT").expect("Commit");

        conn.execute("BEGIN").expect("Failed to start tx");
        insert_status_changed_event(&conn, "test-001", "alice", "open", "in_progress")
            .expect("Status change");
        conn.execute("COMMIT").expect("Commit");

        conn.execute("BEGIN").expect("Failed to start tx");
        insert_commented_event(&conn, "test-001", "bob", "Working on this").expect("Comment");
        conn.execute("COMMIT").expect("Commit");

        conn.execute("BEGIN").expect("Failed to start tx");
        insert_closed_event(&conn, "test-001", "alice", Some("Done")).expect("Closed");
        conn.execute("COMMIT").expect("Commit");

        let events = get_events(&conn, "test-001", 0).expect("Failed to get events");
        assert_eq!(events.len(), 4);

        // Verify order (newest first)
        assert_eq!(events[0].event_type, EventType::Closed);
        assert_eq!(events[1].event_type, EventType::Commented);
        assert_eq!(events[2].event_type, EventType::StatusChanged);
        assert_eq!(events[3].event_type, EventType::Created);
    }

    #[test]
    fn test_get_events_errors_on_invalid_timestamp() {
        let conn = setup_test_db();

        conn.execute("BEGIN").expect("Failed to start tx");
        conn.execute_with_params(
            "INSERT INTO events (issue_id, event_type, actor, created_at) VALUES (?1, ?2, ?3, ?4)",
            &[
                SqliteValue::from("test-001"),
                SqliteValue::from("created"),
                SqliteValue::from("alice"),
                SqliteValue::from("definitely-not-a-timestamp"),
            ],
        )
        .expect("insert malformed event");
        conn.execute("COMMIT").expect("commit malformed event");

        let err = get_events(&conn, "test-001", 0).unwrap_err();
        match err {
            BeadsError::Config(msg) => assert!(msg.contains("Invalid event timestamp")),
            other => panic!("unexpected error: {other:?}"),
        }
    }
}