breakrs 0.2.1

A simple, ergonomic CLI timer for taking breaks
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
//! Timer database with persistence and concurrency control.
//!
//! This module provides a JSON-based database for storing active timers and
//! timer history, with file locking to prevent corruption from concurrent access.

use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::PathBuf;
use time::OffsetDateTime;
use uuid::Uuid;

// Time constants to avoid magic numbers
const SECONDS_PER_MINUTE: u64 = 60;
const SECONDS_PER_HOUR: u64 = 60 * SECONDS_PER_MINUTE; // 3600
const SECONDS_PER_DAY: u64 = 24 * SECONDS_PER_HOUR; // 86400
const SECONDS_PER_YEAR: u64 = 365 * SECONDS_PER_DAY; // 31,536,000
const DAYS_PER_TWO_YEARS: i64 = 730;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Timer {
    pub uuid: Uuid,
    pub id: u32,
    pub message: String,
    pub duration_seconds: u64,
    #[serde(with = "time::serde::timestamp")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp")]
    pub due_at: OffsetDateTime,
    #[serde(default)]
    pub urgent: bool,
    #[serde(default)]
    pub sound: bool,
    #[serde(default)]
    pub recurring: bool,
}

/// Maximum number of active timers allowed to prevent resource exhaustion
const MAX_TIMERS: usize = 100;

#[derive(Debug, Serialize, Deserialize)]
pub struct Database {
    pub timers: Vec<Timer>,
    #[serde(default)]
    pub history: Vec<Timer>,
    next_id: u32,
}

impl Database {
    pub fn new() -> Self {
        Self {
            timers: Vec::new(),
            history: Vec::new(),
            next_id: 1,
        }
    }

    /// Validates a timer to ensure it has reasonable data.
    ///
    /// Filters out corrupted or invalid timers that could cause issues.
    ///
    /// # Arguments
    ///
    /// * `timer` - The timer to validate
    ///
    /// # Returns
    ///
    /// Returns `true` if the timer is valid, `false` if it should be filtered out.
    fn is_valid_timer(timer: &Timer) -> bool {
        let now = OffsetDateTime::now_utc();

        // Filter out timers with empty messages
        if timer.message.trim().is_empty() {
            return false;
        }

        // Filter out timers with timestamps too far in the past (> 2 years old)
        // This catches corrupted timestamps or very old stale timers
        let two_years_ago = now - time::Duration::days(DAYS_PER_TWO_YEARS);
        if timer.created_at < two_years_ago {
            return false;
        }

        // Filter out timers with invalid durations (> 1 year)
        if timer.duration_seconds > SECONDS_PER_YEAR {
            return false;
        }

        // Filter out timers with due dates unreasonably far in the future (> 2 years)
        let two_years_future = now + time::Duration::days(DAYS_PER_TWO_YEARS);
        if timer.due_at > two_years_future {
            return false;
        }

        true
    }

    /// Validates and cleans the database after loading.
    ///
    /// Removes any invalid timers and ensures the database is in a consistent state.
    fn validate_and_clean(&mut self) {
        let original_count = self.timers.len();
        self.timers.retain(Self::is_valid_timer);

        let removed = original_count - self.timers.len();
        if removed > 0 {
            eprintln!(
                "Warning: Removed {} invalid timer(s) from database",
                removed
            );
        }
    }

    /// Loads the database from disk with a shared lock for read-only access.
    ///
    /// Multiple readers can access the database simultaneously. This is suitable for
    /// operations like listing timers or checking status that don't modify the database.
    ///
    /// # Returns
    ///
    /// Returns a new `Database` instance if the file doesn't exist, or loads the
    /// existing database from `~/.local/share/break/timers.json`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The database file is corrupted or contains invalid JSON
    /// - File permissions prevent reading
    /// - The data directory cannot be accessed
    pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
        let path = Self::db_path()?;

        if !path.exists() {
            return Ok(Self::new());
        }

        // Open file with shared lock (multiple readers allowed)
        let file = File::open(&path)?;
        FileExt::lock_shared(&file)?;

        let mut contents = String::new();
        let mut reader = std::io::BufReader::new(&file);
        reader.read_to_string(&mut contents)?;

        // Parse JSON with better error messages
        let mut db: Database = serde_json::from_str(&contents).map_err(|e| {
            format!(
                "Database file is corrupted or invalid. Error: {}\nLocation: {}\nTo fix: Delete the file and restart.",
                e,
                path.display()
            )
        })?;

        // Validate and clean the loaded database
        db.validate_and_clean();

        FileExt::unlock(&file)?;
        Ok(db)
    }

    /// Executes a load-modify-save transaction with an exclusive lock held throughout.
    ///
    /// This ensures atomic database updates by holding an exclusive file lock for the
    /// entire operation. Only one writer can execute a transaction at a time, preventing
    /// race conditions and data corruption from concurrent modifications.
    ///
    /// # Arguments
    ///
    /// * `f` - A closure that receives a mutable reference to the database and returns
    ///   a result. The closure can modify the database freely, and changes are
    ///   automatically saved when the closure completes successfully.
    ///
    /// # Returns
    ///
    /// Returns the value returned by the closure on success.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The database file cannot be opened or locked
    /// - The database file is corrupted
    /// - The closure returns an error
    /// - Saving the modified database fails
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use breakrs::database::Database;
    /// Database::with_transaction(|db| {
    ///     db.add_timer("Coffee break".to_string(), 300, false, false, false)?;
    ///     Ok(())
    /// })?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn with_transaction<F, T>(mut f: F) -> Result<T, Box<dyn std::error::Error>>
    where
        F: FnMut(&mut Database) -> Result<T, Box<dyn std::error::Error>>,
    {
        let path = Self::db_path()?;

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        // Open/create file with exclusive lock for entire transaction
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false) // Don't truncate - we need to read existing data first
            .open(&path)?;

        FileExt::lock_exclusive(&file)?;

        // Load database
        let mut db = if file.metadata()?.len() == 0 {
            // Empty file, create new database
            Self::new()
        } else {
            let mut contents = String::new();
            let mut reader = std::io::BufReader::new(&file);
            reader.read_to_string(&mut contents)?;

            let mut db: Database = serde_json::from_str(&contents).map_err(|e| {
                format!(
                    "Database file is corrupted or invalid. Error: {}\nLocation: {}\nTo fix: Delete the file and restart.",
                    e,
                    path.display()
                )
            })?;

            // Validate and clean the loaded database
            db.validate_and_clean();
            db
        };

        // Run the transaction function
        let result = f(&mut db)?;

        // Save database
        let contents = serde_json::to_string_pretty(&db)?;
        let file = OpenOptions::new().write(true).truncate(true).open(&path)?;
        let mut writer = std::io::BufWriter::new(&file);
        writer.write_all(contents.as_bytes())?;
        writer.flush()?;

        FileExt::unlock(&file)?;

        Ok(result)
    }

    /// Save database (use with_transaction instead for modifications)
    pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
        let path = Self::db_path()?;

        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        // Open/create file with exclusive lock (only one writer)
        let file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&path)?;

        FileExt::lock_exclusive(&file)?;

        let contents = serde_json::to_string_pretty(self)?;
        let mut writer = std::io::BufWriter::new(&file);
        writer.write_all(contents.as_bytes())?;
        writer.flush()?;

        FileExt::unlock(&file)?;
        Ok(())
    }

    /// Adds a new timer to the database.
    ///
    /// # Arguments
    ///
    /// * `message` - The timer message to display when it expires
    /// * `duration_seconds` - Duration in seconds (max 1 year)
    /// * `urgent` - Whether to mark notification as urgent/critical
    /// * `sound` - Whether to play sound with notification
    /// * `recurring` - Whether timer should repeat after completion
    ///
    /// # Returns
    ///
    /// Returns the created `Timer` with assigned ID and calculated due time.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The duration exceeds 1 year (31,536,000 seconds)
    /// - The maximum number of active timers (100) has been reached
    pub fn add_timer(
        &mut self,
        message: String,
        duration_seconds: u64,
        urgent: bool,
        sound: bool,
        recurring: bool,
    ) -> Result<Timer, String> {
        // Check maximum timer limit
        if self.timers.len() >= MAX_TIMERS {
            return Err(format!(
                "Maximum number of active timers ({}) reached. Please remove some timers first.",
                MAX_TIMERS
            ));
        }

        // Validate duration is reasonable (max 1 year = 31,536,000 seconds)
        if duration_seconds > SECONDS_PER_YEAR {
            return Err(format!(
                "Duration too large (max {} days)",
                SECONDS_PER_YEAR / SECONDS_PER_DAY
            ));
        }

        let now = OffsetDateTime::now_utc();
        let due_at = now + time::Duration::seconds(duration_seconds as i64);

        let timer = Timer {
            uuid: Uuid::new_v4(),
            id: self.next_id,
            message,
            duration_seconds,
            created_at: now,
            due_at,
            urgent,
            sound,
            recurring,
        };

        self.next_id += 1;
        self.timers.push(timer.clone());
        Ok(timer)
    }

    /// Resets a timer to start over from the current time.
    ///
    /// This is primarily used for recurring timers that need to repeat after completion.
    /// The timer's `created_at` is set to now and `due_at` is recalculated based on
    /// the original duration.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the timer to reset
    ///
    /// # Returns
    ///
    /// Returns `Some(Timer)` with the updated timer if found, `None` if no timer
    /// with the given ID exists.
    pub fn reset_timer(&mut self, id: u32) -> Option<Timer> {
        if let Some(timer) = self.timers.iter_mut().find(|t| t.id == id) {
            let now = OffsetDateTime::now_utc();
            timer.due_at = now + time::Duration::seconds(timer.duration_seconds as i64);
            timer.created_at = now;
            Some(timer.clone())
        } else {
            None
        }
    }

    /// Removes a timer from the active timers list without adding it to history.
    ///
    /// This is used when a user explicitly cancels/removes a timer. For timers that
    /// complete naturally, use `complete_timer()` instead to add them to history.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the timer to remove
    ///
    /// # Returns
    ///
    /// Returns `Some(Timer)` containing the removed timer if found, `None` if no
    /// timer with the given ID exists.
    pub fn remove_timer(&mut self, id: u32) -> Option<Timer> {
        if let Some(pos) = self.timers.iter().position(|t| t.id == id) {
            Some(self.timers.remove(pos))
        } else {
            None
        }
    }

    /// Completes a timer by removing it from active timers and adding it to history.
    ///
    /// This is the proper way to handle timer expiration. The timer is removed from
    /// the active list and added to the front of the history list for tracking purposes.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the timer to complete
    ///
    /// # Returns
    ///
    /// Returns `Some(Timer)` containing the completed timer if found, `None` if no
    /// timer with the given ID exists.
    pub fn complete_timer(&mut self, id: u32) -> Option<Timer> {
        if let Some(pos) = self.timers.iter().position(|t| t.id == id) {
            let timer = self.timers.remove(pos);
            self.add_to_history(timer.clone());
            Some(timer)
        } else {
            None
        }
    }

    /// Adds a completed timer to the history list.
    ///
    /// History is maintained as a most-recent-first list with a maximum of 20 entries.
    /// When the limit is exceeded, the oldest entries are removed.
    ///
    /// This allows users to see recently completed timers even if they missed the
    /// notification.
    ///
    /// # Arguments
    ///
    /// * `timer` - The timer to add to history
    pub fn add_to_history(&mut self, timer: Timer) {
        const MAX_HISTORY: usize = 20;

        // Add to front of history (most recent first)
        self.history.insert(0, timer);

        // Keep only last MAX_HISTORY entries
        if self.history.len() > MAX_HISTORY {
            self.history.truncate(MAX_HISTORY);
        }
    }

    /// Clears all active timers.
    ///
    /// This removes all timers from the active list without adding them to history.
    /// Used when the user wants to cancel all pending timers at once.
    pub fn clear_all(&mut self) {
        self.timers.clear();
    }

    /// Clears the history of completed timers.
    ///
    /// This removes all entries from the history list, providing a fresh start
    /// for tracking recently completed timers.
    pub fn clear_history(&mut self) {
        self.history.clear();
    }

    /// Returns all timers that have expired (due_at is in the past).
    ///
    /// This is used by the daemon to identify which timers need to fire notifications.
    /// Timers are considered expired when their `due_at` time is less than or equal
    /// to the current UTC time.
    ///
    /// # Returns
    ///
    /// A vector containing clones of all expired timers. Returns an empty vector
    /// if no timers have expired.
    pub fn get_expired_timers(&self) -> Vec<Timer> {
        let now = OffsetDateTime::now_utc();
        self.timers
            .iter()
            .filter(|t| t.due_at <= now)
            .cloned()
            .collect()
    }

    fn db_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
        let data_dir = dirs::data_dir().ok_or("Could not find data directory")?;
        Ok(data_dir.join("break").join("timers.json"))
    }
}

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

    #[test]
    fn test_new_database() {
        let db = Database::new();
        assert_eq!(db.timers.len(), 0);
        assert_eq!(db.history.len(), 0);
        assert_eq!(db.next_id, 1);
    }

    #[test]
    fn test_add_timer() {
        let mut db = Database::new();
        let timer = db
            .add_timer("Test".to_string(), 300, false, false, false)
            .unwrap();

        assert_eq!(timer.id, 1);
        assert_eq!(timer.message, "Test");
        assert_eq!(timer.duration_seconds, 300);
        assert_eq!(db.timers.len(), 1);
        assert_eq!(db.next_id, 2);
    }

    #[test]
    fn test_add_timer_max_duration() {
        let mut db = Database::new();

        // Should succeed at max duration
        let result = db.add_timer("Max".to_string(), SECONDS_PER_YEAR, false, false, false);
        assert!(result.is_ok());

        // Should fail above max duration
        let result = db.add_timer(
            "Too long".to_string(),
            SECONDS_PER_YEAR + 1,
            false,
            false,
            false,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Duration too large"));
    }

    #[test]
    fn test_remove_timer() {
        let mut db = Database::new();
        let timer = db
            .add_timer("Test".to_string(), 300, false, false, false)
            .unwrap();

        let removed = db.remove_timer(timer.id);
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().id, timer.id);
        assert_eq!(db.timers.len(), 0);

        // Removing non-existent timer should return None
        let removed = db.remove_timer(999);
        assert!(removed.is_none());
    }

    #[test]
    fn test_complete_timer() {
        let mut db = Database::new();
        let timer = db
            .add_timer("Test".to_string(), 300, false, false, false)
            .unwrap();

        let completed = db.complete_timer(timer.id);
        assert!(completed.is_some());
        assert_eq!(db.timers.len(), 0);
        assert_eq!(db.history.len(), 1);
        assert_eq!(db.history[0].id, timer.id);
    }

    #[test]
    fn test_reset_timer() {
        let mut db = Database::new();
        let timer = db
            .add_timer("Test".to_string(), 300, false, false, false)
            .unwrap();
        let original_due = timer.due_at;

        // Wait a tiny bit and reset
        std::thread::sleep(std::time::Duration::from_millis(10));

        let reset = db.reset_timer(timer.id);
        assert!(reset.is_some());

        // Due time should be updated (different from original)
        let reset_timer = reset.unwrap();
        assert!(reset_timer.created_at > timer.created_at);
        assert!(reset_timer.due_at > original_due);
    }

    #[test]
    fn test_history_max_entries() {
        let mut db = Database::new();

        // Add 25 timers and complete them all
        for i in 1..=25 {
            let timer = db
                .add_timer(format!("Timer {}", i), 10, false, false, false)
                .unwrap();
            db.complete_timer(timer.id);
        }

        // Should only keep last 20
        assert_eq!(db.history.len(), 20);

        // Most recent should be first (Timer 25)
        assert_eq!(db.history[0].message, "Timer 25");
        // Oldest in history should be Timer 6 (25 - 20 + 1)
        assert_eq!(db.history[19].message, "Timer 6");
    }

    #[test]
    fn test_clear_all() {
        let mut db = Database::new();
        db.add_timer("Test 1".to_string(), 300, false, false, false)
            .unwrap();
        db.add_timer("Test 2".to_string(), 600, false, false, false)
            .unwrap();

        assert_eq!(db.timers.len(), 2);
        db.clear_all();
        assert_eq!(db.timers.len(), 0);

        // History should not be affected
        db.add_to_history(Timer {
            uuid: uuid::Uuid::new_v4(),
            id: 1,
            message: "History".to_string(),
            duration_seconds: 100,
            created_at: OffsetDateTime::now_utc(),
            due_at: OffsetDateTime::now_utc(),
            urgent: false,
            sound: false,
            recurring: false,
        });
        assert_eq!(db.history.len(), 1);
        db.clear_all();
        assert_eq!(db.history.len(), 1); // Still there
    }

    #[test]
    fn test_clear_history() {
        let mut db = Database::new();
        let timer = db
            .add_timer("Test".to_string(), 300, false, false, false)
            .unwrap();
        db.complete_timer(timer.id);

        assert_eq!(db.history.len(), 1);
        db.clear_history();
        assert_eq!(db.history.len(), 0);
    }

    #[test]
    fn test_get_expired_timers() {
        let mut db = Database::new();

        // Add a timer that's already expired (0 seconds)
        let expired_timer = db
            .add_timer("Expired".to_string(), 0, false, false, false)
            .unwrap();

        // Add a future timer
        db.add_timer("Future".to_string(), SECONDS_PER_HOUR, false, false, false)
            .unwrap();

        // Small delay to ensure the 0-second timer is definitely expired
        std::thread::sleep(std::time::Duration::from_millis(10));

        let expired = db.get_expired_timers();
        assert_eq!(expired.len(), 1);
        assert_eq!(expired[0].id, expired_timer.id);
    }

    #[test]
    fn test_timer_flags() {
        let mut db = Database::new();

        // Test all flags
        let timer = db
            .add_timer("Urgent sound recurring".to_string(), 300, true, true, true)
            .unwrap();
        assert!(timer.urgent);
        assert!(timer.sound);
        assert!(timer.recurring);

        // Test default flags
        let timer = db
            .add_timer("Default".to_string(), 300, false, false, false)
            .unwrap();
        assert!(!timer.urgent);
        assert!(!timer.sound);
        assert!(!timer.recurring);
    }

    #[test]
    fn test_sequential_ids() {
        let mut db = Database::new();

        let timer1 = db
            .add_timer("First".to_string(), 300, false, false, false)
            .unwrap();
        let timer2 = db
            .add_timer("Second".to_string(), 300, false, false, false)
            .unwrap();
        let timer3 = db
            .add_timer("Third".to_string(), 300, false, false, false)
            .unwrap();

        assert_eq!(timer1.id, 1);
        assert_eq!(timer2.id, 2);
        assert_eq!(timer3.id, 3);

        // Even after removing, next ID should continue
        db.remove_timer(timer2.id);
        let timer4 = db
            .add_timer("Fourth".to_string(), 300, false, false, false)
            .unwrap();
        assert_eq!(timer4.id, 4);
    }

    #[test]
    fn test_max_timers_limit() {
        let mut db = Database::new();

        // Add MAX_TIMERS (100) timers - should succeed
        for i in 1..=100 {
            let result = db.add_timer(format!("Timer {}", i), 300, false, false, false);
            assert!(result.is_ok(), "Should be able to add timer {}", i);
        }

        assert_eq!(db.timers.len(), 100);

        // Adding one more should fail
        let result = db.add_timer("Timer 101".to_string(), 300, false, false, false);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Maximum number"));

        // After removing one, should be able to add again
        db.remove_timer(1);
        let result = db.add_timer("Timer 101".to_string(), 300, false, false, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_timer_empty_message() {
        let now = OffsetDateTime::now_utc();
        let timer = Timer {
            uuid: Uuid::new_v4(),
            id: 1,
            message: "   ".to_string(), // Empty after trim
            duration_seconds: 300,
            created_at: now,
            due_at: now + time::Duration::seconds(300),
            urgent: false,
            sound: false,
            recurring: false,
        };

        assert!(!Database::is_valid_timer(&timer));
    }

    #[test]
    fn test_validate_timer_old_timestamp() {
        let now = OffsetDateTime::now_utc();
        let three_years_ago = now - time::Duration::days(1095);

        let timer = Timer {
            uuid: Uuid::new_v4(),
            id: 1,
            message: "Old timer".to_string(),
            duration_seconds: 300,
            created_at: three_years_ago, // Too old
            due_at: now + time::Duration::seconds(300),
            urgent: false,
            sound: false,
            recurring: false,
        };

        assert!(!Database::is_valid_timer(&timer));
    }

    #[test]
    fn test_validate_timer_excessive_duration() {
        let now = OffsetDateTime::now_utc();
        let timer = Timer {
            uuid: Uuid::new_v4(),
            id: 1,
            message: "Long timer".to_string(),
            duration_seconds: 500 * SECONDS_PER_DAY, // > 1 year
            created_at: now,
            due_at: now + time::Duration::days(500),
            urgent: false,
            sound: false,
            recurring: false,
        };

        assert!(!Database::is_valid_timer(&timer));
    }

    #[test]
    fn test_validate_timer_far_future() {
        let now = OffsetDateTime::now_utc();
        let three_years_future = now + time::Duration::days(1095);

        let timer = Timer {
            uuid: Uuid::new_v4(),
            id: 1,
            message: "Future timer".to_string(),
            duration_seconds: 300,
            created_at: now,
            due_at: three_years_future, // Too far in future
            urgent: false,
            sound: false,
            recurring: false,
        };

        assert!(!Database::is_valid_timer(&timer));
    }

    #[test]
    fn test_validate_timer_valid() {
        let now = OffsetDateTime::now_utc();
        let timer = Timer {
            uuid: Uuid::new_v4(),
            id: 1,
            message: "Valid timer".to_string(),
            duration_seconds: 300,
            created_at: now,
            due_at: now + time::Duration::seconds(300),
            urgent: false,
            sound: false,
            recurring: false,
        };

        assert!(Database::is_valid_timer(&timer));
    }

    #[test]
    fn test_validate_and_clean() {
        let mut db = Database::new();
        let now = OffsetDateTime::now_utc();

        // Add a valid timer
        db.timers.push(Timer {
            uuid: Uuid::new_v4(),
            id: 1,
            message: "Valid".to_string(),
            duration_seconds: 300,
            created_at: now,
            due_at: now + time::Duration::seconds(300),
            urgent: false,
            sound: false,
            recurring: false,
        });

        // Add an invalid timer (empty message)
        db.timers.push(Timer {
            uuid: Uuid::new_v4(),
            id: 2,
            message: "".to_string(),
            duration_seconds: 300,
            created_at: now,
            due_at: now + time::Duration::seconds(300),
            urgent: false,
            sound: false,
            recurring: false,
        });

        // Add another invalid timer (too old)
        db.timers.push(Timer {
            uuid: Uuid::new_v4(),
            id: 3,
            message: "Old".to_string(),
            duration_seconds: 300,
            created_at: now - time::Duration::days(1000),
            due_at: now + time::Duration::seconds(300),
            urgent: false,
            sound: false,
            recurring: false,
        });

        assert_eq!(db.timers.len(), 3);

        db.validate_and_clean();

        // Only the valid timer should remain
        assert_eq!(db.timers.len(), 1);
        assert_eq!(db.timers[0].message, "Valid");
    }
}