kasl-cli 1.0.0

kasl is a comprehensive command-line utility 🛠️ designed to streamline the tracking of work activities 📊, including start times ⏰, pauses ⏸, and task completion
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
//! Database operations for tracking pause periods.
//!
//! Manages the storage and retrieval of pause records during work sessions:
//! absences detected automatically by the activity monitor, and ones the user
//! recorded by hand because the monitor could not see them.
//!
//! ## Features
//!
//! - **Automatic Detection**: Records pauses when user activity stops
//! - **Manual Entry**: Records a complete pause with user-stated bounds
//! - **Protection**: Manual pauses can bypass threshold filtering and merging
//! - **Duration Calculation**: Automatic computation of pause lengths
//! - **Daily Filtering**: Retrieve pauses for specific dates with duration thresholds
//! - **Batch Operations**: Delete multiple pause records efficiently
//!
//! ## Usage
//!
//! ```rust,no_run
//! # fn main() -> anyhow::Result<()> {
//! use kasl::db::pauses::Pauses;
//!
//! let pauses = Pauses::new()?;
//! pauses.insert_start()?;
//! pauses.insert_end()?; // completes the most recent open pause
//! # Ok(())
//! # }
//! ```

use crate::db::db::Db;
use crate::db::workdays::Workday;
use crate::libs::config::Config;
use crate::libs::pause::Pause;
use anyhow::Result;
use chrono::{Local, NaiveDate, NaiveDateTime, TimeDelta};
use parking_lot::Mutex;
use rusqlite::{Connection, params};
use std::sync::Arc;

/// SQL schema for the pauses table.
///
/// Defines the structure for storing pause/break records with temporal data.
/// The schema supports both ongoing pauses (end IS NULL) and completed pauses
/// with calculated durations for reporting and analysis.
const SCHEMA_PAUSES: &str = "CREATE TABLE IF NOT EXISTS pauses (
    id INTEGER NOT NULL PRIMARY KEY,
    start TIMESTAMP NOT NULL,
    end TIMESTAMP,
    duration INTEGER,
    protected INTEGER NOT NULL DEFAULT 0,
    reason TEXT
)";

/// Insert a new pause start record with the current timestamp.
///
/// This query creates a new pause record with only the start time set,
/// leaving end and duration as NULL until the pause is completed.
const INSERT_PAUSE: &str = "INSERT INTO pauses (start) VALUES (datetime(CURRENT_TIMESTAMP, 'localtime'))";

/// Insert a new pause start record with a specific timestamp.
///
/// Used for manually adding pauses or when importing historical data
/// where the exact start time is known.
const INSERT_PAUSE_WITH_TIME: &str = "INSERT INTO pauses (start) VALUES (?1)";

/// Update the most recent open pause with end time and calculated duration.
///
/// Completes a pause record by setting the end timestamp and storing
/// the calculated duration in seconds for later analysis.
const UPDATE_PAUSE: &str = "UPDATE pauses SET end = (datetime(CURRENT_TIMESTAMP, 'localtime')), duration = ?1 WHERE id = ?2";

/// Select the most recent uncompleted pause record.
///
/// Finds the last pause that has a start time but no end time,
/// indicating an ongoing pause that needs to be completed.
const SELECT_LAST_PAUSE: &str = "SELECT id, start FROM pauses WHERE end IS NULL ORDER BY id DESC LIMIT 1";

/// Select all completed pauses for a specific date.
///
/// Retrieves every completed pause (end IS NOT NULL) for the given date
/// ordered chronologically. Duration filtering is performed in Rust after
/// merging consecutive pauses, so no threshold is applied here.
const SELECT_DAILY_PAUSES: &str =
    "SELECT id, start, end, duration, protected FROM pauses WHERE date(start) = date(?1) AND end IS NOT NULL ORDER BY start ASC, id ASC";

/// Insert a complete manual pause with explicit start, end and duration.
///
/// Used by `kasl pauses add`, where the user states when they were away
/// instead of the monitor detecting it. `protected` decides whether the
/// record is exempt from threshold filtering and merging.
const INSERT_MANUAL_PAUSE: &str = "INSERT INTO pauses (start, end, duration, protected, reason) VALUES (?1, ?2, ?3, ?4, ?5)";

/// Delete a single pause record by ID.
///
/// Removes a pause record from the database, typically used for
/// correcting incorrectly recorded pauses or data cleanup.
const DELETE_PAUSE: &str = "DELETE FROM pauses WHERE id = ?";

/// Database manager for pause/break tracking operations.
///
/// The `Pauses` struct provides a high-level interface for managing work break
/// records in the database. It uses thread-safe connection handling to support
/// concurrent access from the activity monitor and user commands.
///
/// ## Thread Safety
///
/// The connection is wrapped in an `Arc<Mutex<>>` to allow safe concurrent access
/// from multiple threads, particularly important when the activity monitor
/// is running in the background while users interact with the CLI.
///
/// ## Connection Management
///
/// Each `Pauses` instance maintains its own database connection and ensures
/// the pauses table schema is properly initialized on creation.
pub struct Pauses {
    /// Thread-safe database connection wrapper.
    ///
    /// The connection is protected by a mutex to prevent race conditions
    /// when multiple threads attempt to record or query pause data
    /// simultaneously.
    pub conn: Arc<Mutex<Connection>>,
    pub min_duration: Option<String>,
    pub max_duration: Option<String>,
}

impl Pauses {
    /// Creates a new `Pauses` instance and initializes the database schema.
    ///
    /// This constructor establishes a database connection, ensures the pauses
    /// table exists with the proper schema, and wraps the connection for
    /// thread-safe access. The schema creation is idempotent and safe to
    /// call multiple times.
    ///
    /// # Returns
    ///
    /// Returns a new `Pauses` instance ready for pause tracking operations,
    /// or an error if database initialization fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # fn main() -> anyhow::Result<()> {
    /// use kasl::db::pauses::Pauses;
    ///
    /// let pauses = Pauses::new()?;
    /// // Ready to track pauses
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Database connection cannot be established
    /// - Schema creation fails due to permissions or corruption
    /// - Table initialization encounters SQL errors
    pub fn new() -> Result<Pauses> {
        // Establish database connection through the central Db manager
        let db_conn = Db::new()?.conn;

        // Initialize the pauses table schema if it doesn't exist
        db_conn.execute(SCHEMA_PAUSES, [])?;

        // Wrap connection for thread-safe access
        Ok(Pauses {
            conn: Arc::new(Mutex::new(db_conn)),
            min_duration: None,
            max_duration: None,
        })
    }

    pub fn set_min_duration(&self, min_duration: u64) -> Self {
        let min_duration_secs = (min_duration * 60) as i64; // Convert minutes to seconds
        Self {
            conn: self.conn.clone(),
            min_duration: Some(min_duration_secs.to_string()),
            max_duration: None,
        }
    }

    pub fn set_max_duration(&self, max_duration: u64) -> Self {
        let max_duration_secs = (max_duration * 60) as i64; // Convert minutes to second
        Self {
            conn: self.conn.clone(),
            min_duration: None,
            max_duration: Some(max_duration_secs.to_string()),
        }
    }

    /// Merges consecutive pauses separated only by an insignificant work gap.
    ///
    /// The activity monitor can split a single, effectively continuous break into
    /// several adjacent pause records separated by brief bursts of activity (a
    /// stray mouse move, a few seconds of typing). Because a duration threshold is
    /// applied per-record, some of these segments may individually fall below the
    /// threshold and be discarded, even though together they form one long pause.
    /// Merging such chains before filtering ensures they are treated as a single
    /// pause.
    ///
    /// Two pauses are merged when the gap between the end of one and the start of
    /// the next does not exceed `max_gap_secs` (a work interval shorter than this
    /// is not considered meaningful work). The merged pause keeps the earliest
    /// start, the latest end, and its duration is recomputed as `end - start`.
    ///
    /// The input is expected to be sorted chronologically by start time.
    /// Protected pauses never participate in merging: they were stated by the
    /// user with explicit bounds, so absorbing them into a neighbour (or
    /// absorbing a neighbour into them) would falsify what the user recorded.
    fn merge_consecutive_pauses(pauses: Vec<Pause>, max_gap_secs: i64) -> Vec<Pause> {
        let mut merged: Vec<Pause> = Vec::with_capacity(pauses.len());

        for pause in pauses {
            if pause.protected {
                merged.push(pause);
                continue;
            }

            if let Some(last) = merged.last_mut()
                && !last.protected
                && let Some(last_end) = last.end
            {
                // Merge when the work gap between the pauses is small enough
                // (contiguous, overlapping, or a negligible burst of activity).
                let gap = (pause.start - last_end).num_seconds();
                if gap <= max_gap_secs {
                    let new_end = match pause.end {
                        Some(end) => Some(end.max(last_end)),
                        None => Some(last_end),
                    };
                    last.end = new_end;
                    if let Some(end) = last.end {
                        last.duration = Some(TimeDelta::seconds((end - last.start).num_seconds()));
                    }
                    continue;
                }
            }
            merged.push(pause);
        }

        merged
    }

    /// Returns the active duration threshold in seconds, if any is configured.
    ///
    /// Positive value with `min` semantics is expressed through `min_duration`,
    /// `max` semantics through `max_duration`. Only one of them is ever set.
    fn duration_threshold_seconds(&self) -> Option<i64> {
        self.min_duration.as_ref().or(self.max_duration.as_ref()).and_then(|d| d.parse::<i64>().ok())
    }

    /// Records the start of a new pause with the current timestamp.
    ///
    /// This method creates a new pause record using the current system time
    /// as the start timestamp. The pause remains "open" (end IS NULL) until
    /// it's completed with `insert_end()`. Multiple open pauses are allowed
    /// to handle edge cases in activity detection.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the pause start is recorded successfully,
    /// or an error if the database operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// pauses.insert_start()?; // Pause started at current time
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from
    /// multiple threads, such as the activity monitor daemon.
    pub fn insert_start(&self) -> rusqlite::Result<()> {
        let conn_guard = self.conn.lock();
        conn_guard.execute(INSERT_PAUSE, [])?;
        Ok(())
    }

    /// Records the start of a new pause with a specific timestamp.
    ///
    /// This method allows manual insertion of pause records with exact
    /// timestamps, useful for importing historical data or correcting
    /// activity tracking records. The specified time should be in the
    /// local timezone for consistency with other records.
    ///
    /// # Arguments
    ///
    /// * `start_time` - The exact timestamp when the pause began
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the pause is recorded successfully,
    /// or an error if the database operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// use chrono::NaiveDateTime;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// let start_time = NaiveDateTime::parse_from_str(
    ///     "2025-01-15 14:30:00",
    ///     "%Y-%m-%d %H:%M:%S"
    /// )?;
    /// pauses.insert_start_with_time(start_time)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Data Integrity
    ///
    /// The caller is responsible for ensuring the timestamp is reasonable
    /// and doesn't conflict with existing work session boundaries.
    pub fn insert_start_with_time(&self, start_time: NaiveDateTime) -> Result<()> {
        let conn_guard = self.conn.lock();
        let start_str = start_time.format("%Y-%m-%d %H:%M:%S").to_string();
        conn_guard.execute(INSERT_PAUSE_WITH_TIME, [&start_str])?;
        Ok(())
    }

    /// Completes the most recent open pause with duration calculation.
    ///
    /// This method finds the last pause record that has a start time but no
    /// end time, then updates it with the current timestamp and the provided
    /// duration. The duration is typically calculated by the activity monitor
    /// based on the actual inactive period.
    ///
    /// ## Duration Calculation
    ///
    /// While the end timestamp is set to the current time, the duration
    /// parameter contains the actual pause length in seconds. This allows
    /// for accurate tracking even when there's a delay between activity
    /// resumption and pause recording.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the pause is completed successfully, or an error
    /// if no open pause exists or the database operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// pauses.insert_start()?;
    /// // ... user is inactive for 5 minutes ...
    /// pauses.insert_end()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Behavior Notes
    ///
    /// - Only affects the most recent open pause record
    /// - If no open pause exists, the operation may fail silently
    /// - Duration should be a positive number of seconds
    pub fn insert_end(&self) -> Result<()> {
        let end = Local::now().naive_local();
        let conn_guard = self.conn.lock();

        let mut stmt = conn_guard.prepare(SELECT_LAST_PAUSE)?;
        let pause_row = stmt.query_row([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)));
        if let Ok((id, start_str)) = pause_row {
            let start = NaiveDateTime::parse_from_str(&start_str, "%Y-%m-%d %H:%M:%S")?;
            let duration = (end - start).num_seconds();
            conn_guard.execute(UPDATE_PAUSE, [&duration.to_string(), &id.to_string()])?;
        }

        Ok(())
    }

    /// Records a complete pause stated by the user, with explicit bounds.
    ///
    /// Unlike monitor-detected pauses, which are opened by `insert_start` and
    /// closed later by `insert_end`, a manual pause is written in one shot: the
    /// user knows when they left and how long they were gone. No placement is
    /// inferred and no time is invented.
    ///
    /// # Arguments
    ///
    /// * `start` - When the absence began
    /// * `duration` - How long it lasted
    /// * `protected` - Exempt the record from threshold filtering and merging
    /// * `reason` - Optional note describing the absence
    ///
    /// # Returns
    ///
    /// Returns the id of the inserted pause record.
    pub fn insert_manual(&self, start: NaiveDateTime, duration: TimeDelta, protected: bool, reason: Option<&str>) -> Result<i64> {
        let end = start + duration;
        let conn_guard = self.conn.lock();
        conn_guard.execute(
            INSERT_MANUAL_PAUSE,
            params![
                start.format("%Y-%m-%d %H:%M:%S").to_string(),
                end.format("%Y-%m-%d %H:%M:%S").to_string(),
                duration.num_seconds(),
                protected as i64,
                reason,
            ],
        )?;
        Ok(conn_guard.last_insert_rowid())
    }

    /// Returns the pause overlapping the given time range, if any exists.
    ///
    /// Used to reject a manual pause that would collide with an already
    /// recorded one, so the day never contains contradictory absences.
    pub fn find_overlapping(&self, start: NaiveDateTime, end: NaiveDateTime) -> Result<Option<Pause>> {
        let pauses = self.get_daily_pauses(start.date())?;
        Ok(pauses.into_iter().find(|p| p.end.map(|p_end| p.start < end && start < p_end).unwrap_or(false)))
    }

    /// Retrieves all pause records for a specific date with duration filtering.
    ///
    /// This method fetches all completed pause records for the given date that
    /// meet or exceed the specified minimum duration threshold. It's commonly
    /// used for daily reporting and work time calculations where very short
    /// pauses (e.g., under 5 minutes) may be ignored.
    ///
    /// ## Filtering Logic
    ///
    /// - Only includes pauses that started on the specified date
    /// - Filters out pauses shorter than the minimum duration
    /// - Includes ongoing pauses (duration IS NULL) regardless of threshold
    /// - Results are ordered by start time for chronological display
    ///
    /// # Arguments
    ///
    /// * `date` - The target date to query (uses local timezone)
    /// * `min_duration` - Minimum pause length to include (in minutes)
    ///
    /// # Returns
    ///
    /// Returns a vector of `Pause` objects representing the filtered pause
    /// records, or an error if the database query fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// use chrono::Local;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// // Get pauses of 10 minutes or longer
    /// let pauses = Pauses::new()?.set_min_duration(10);
    /// let today = Local::now().date_naive();
    ///
    /// let significant_pauses = pauses.get_daily_pauses(today)?;
    /// for pause in significant_pauses {
    ///     println!("Pause: {:?} - {:?}", pause.start, pause.end);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Performance Notes
    ///
    /// This query uses date functions and may be slower on large datasets.
    /// Consider adding indices on the start column for better performance.
    pub fn get_daily_pauses(&self, date: NaiveDate) -> Result<Vec<Pause>> {
        let date_str = date.format("%Y-%m-%d").to_string();
        let conn_guard = self.conn.lock();
        // Fetch all completed pauses for the date, ordered chronologically.
        let mut stmt = conn_guard.prepare(SELECT_DAILY_PAUSES)?;
        let pause_iter = stmt.query_map([&date_str], |row| {
            // Parse timestamps from database strings
            let start_str: String = row.get(1)?;
            let end_str: Option<String> = row.get(2)?;
            let duration: i64 = row.get(3).unwrap_or(0);

            // Create Pause object with parsed data
            Ok(Pause {
                id: row.get(0)?,
                start: NaiveDateTime::parse_from_str(&start_str, "%Y-%m-%d %H:%M:%S").unwrap(),
                end: end_str.map(|s| NaiveDateTime::parse_from_str(&s, "%Y-%m-%d %H:%M:%S").unwrap()),
                duration: Some(TimeDelta::seconds(duration)),
                protected: row.get::<_, i64>(4).unwrap_or(0) != 0,
            })
        })?;

        // Collect results, handling any parsing errors
        let mut pauses = Vec::new();
        for pause_result in pause_iter {
            pauses.push(pause_result?);
        }

        // Merge consecutive pauses separated only by an insignificant gap so that
        // a chain of adjacent pauses (split by a stray input) is treated as a
        // single continuous pause before filtering. The tolerance is the small,
        // dedicated `pause_merge_gap` setting (in seconds): genuine work periods
        // between pauses are longer than this and remain separate.
        let max_gap_secs = Config::read().ok().and_then(|c| c.monitor).map(|m| m.pause_merge_gap as i64).unwrap_or(0);
        let pauses = Self::merge_consecutive_pauses(pauses, max_gap_secs);

        // Apply the configured duration threshold to the merged pauses.
        //
        // Protected pauses bypass the `min_duration` threshold entirely: the user
        // stated them deliberately, so a short manual entry must not be filtered
        // away. The `max_duration` filter is used to isolate *short* pauses for
        // productivity accounting, so protected records are excluded from it —
        // they are accounted for as real, long-form absences.
        let pauses = match (&self.min_duration, &self.max_duration) {
            (Some(_), _) => {
                let min = self.duration_threshold_seconds().unwrap_or(0);
                pauses
                    .into_iter()
                    .filter(|p| p.protected || p.duration.map(|d| d.num_seconds()).unwrap_or(0) >= min)
                    .collect()
            }
            (_, Some(_)) => {
                let max = self.duration_threshold_seconds().unwrap_or(0);
                pauses
                    .into_iter()
                    .filter(|p| !p.protected && p.duration.map(|d| d.num_seconds()).unwrap_or(0) < max)
                    .collect()
            }
            _ => pauses,
        };

        Ok(pauses)
    }

    /// Fetches daily pauses and keeps only the portions inside the workday bounds.
    ///
    /// Drops pauses entirely before `workday.start` or after `workday.end`, and
    /// clips straddling pauses to `[workday.start, workday.end]`.
    pub fn get_workday_pauses(&self, workday: &Workday) -> Result<Vec<Pause>> {
        let pauses = self.get_daily_pauses(workday.date)?;
        Ok(filter_pauses_to_workday(pauses, workday))
    }

    /// Deletes a single pause record by its unique identifier.
    ///
    /// This method removes a specific pause record from the database,
    /// typically used for correcting erroneous pause recordings or
    /// user-requested deletions. The operation is permanent and cannot
    /// be undone without database backups.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the pause record to delete
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the deletion succeeds, or an error if the
    /// database operation fails. Note that deleting a non-existent
    /// record is not considered an error.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// pauses.delete(123)?; // Delete pause with ID 123
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Safety Considerations
    ///
    /// - Deletion is immediate and permanent
    /// - No confirmation prompts are provided at this level
    /// - Callers should implement appropriate confirmation flows
    pub fn delete(&self, id: i32) -> Result<()> {
        let conn_guard = self.conn.lock();
        conn_guard.execute(DELETE_PAUSE, params![id])?;
        Ok(())
    }

    /// Deletes multiple pause records efficiently in a batch operation.
    ///
    /// This method removes multiple pause records in a single transaction,
    /// providing better performance than individual deletions and ensuring
    /// atomicity. If any deletion fails, all changes are rolled back.
    ///
    /// ## Transaction Handling
    ///
    /// All deletions are performed within a single database transaction
    /// to ensure consistency. Either all specified records are deleted
    /// or none are deleted if any error occurs.
    ///
    /// # Arguments
    ///
    /// * `ids` - Slice of pause record IDs to delete
    ///
    /// # Returns
    ///
    /// Returns the number of records actually deleted, or an error if
    /// the batch operation fails. The count may be less than the input
    /// length if some IDs don't exist in the database.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// let ids_to_delete = vec![101, 102, 103];
    /// let deleted_count = pauses.delete_many(&ids_to_delete)?;
    /// println!("Deleted {} pause records", deleted_count);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Performance Benefits
    ///
    /// - Single transaction reduces database overhead
    /// - More efficient than individual delete operations
    /// - Atomic operation ensures data consistency
    ///
    /// # Edge Cases
    ///
    /// - Empty input slice returns 0 without database interaction
    /// - Non-existent IDs are silently ignored
    /// - Partial failures result in complete rollback
    pub fn delete_many(&self, ids: &[i32]) -> Result<usize> {
        // Handle empty input early to avoid unnecessary database operations
        if ids.is_empty() {
            return Ok(0);
        }

        let conn_guard = self.conn.lock();
        let mut deleted = 0;

        // Delete each record individually within the locked connection
        // This could be optimized with a single IN clause query for large batches
        for id in ids {
            deleted += conn_guard.execute(DELETE_PAUSE, params![id])?;
        }

        Ok(deleted)
    }
}

/// Keeps only pause portions that fall inside the workday time bounds.
///
/// - Drops pauses that end at or before `workday.start`
/// - Drops open-ended pauses that start before `workday.start`
/// - Drops pauses that start at or after `workday.end` (when end is set)
/// - Clips straddling pauses to `[workday.start, workday.end]` and recomputes duration
pub fn filter_pauses_to_workday(pauses: Vec<Pause>, workday: &Workday) -> Vec<Pause> {
    let work_start = workday.start;
    let work_end = workday.end;

    pauses
        .into_iter()
        .filter_map(|mut pause| {
            if let Some(end) = pause.end {
                if end <= work_start {
                    return None;
                }
            } else if pause.start < work_start {
                return None;
            }

            if let Some(work_end) = work_end
                && pause.start >= work_end
            {
                return None;
            }

            if pause.start < work_start {
                pause.start = work_start;
            }
            if let (Some(end), Some(work_end)) = (pause.end, work_end)
                && end > work_end
            {
                pause.end = Some(work_end);
            }
            if let Some(end) = pause.end {
                if end <= pause.start {
                    return None;
                }
                pause.duration = Some(end - pause.start);
            }

            Some(pause)
        })
        .collect()
}

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

    fn workday(start: &str, end: Option<&str>) -> Workday {
        Workday {
            id: 1,
            date: NaiveDate::from_ymd_opt(2026, 7, 29).unwrap(),
            start: NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S").unwrap(),
            end: end.map(|e| NaiveDateTime::parse_from_str(e, "%Y-%m-%d %H:%M:%S").unwrap()),
        }
    }

    fn pause(id: i32, start: &str, end: &str) -> Pause {
        let start = NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S").unwrap();
        let end = NaiveDateTime::parse_from_str(end, "%Y-%m-%d %H:%M:%S").unwrap();
        Pause {
            id,
            start,
            end: Some(end),
            duration: Some(end - start),
            protected: false,
        }
    }

    #[test]
    fn drops_pauses_entirely_before_workday_start() {
        let wd = workday("2026-07-29 10:04:30", None);
        let pauses = vec![pause(1, "2026-07-29 10:02:23", "2026-07-29 10:04:26")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert!(filtered.is_empty());
    }

    #[test]
    fn drops_pauses_entirely_after_workday_end() {
        let wd = workday("2026-07-29 10:00:00", Some("2026-07-29 18:00:00"));
        let pauses = vec![pause(1, "2026-07-29 18:30:00", "2026-07-29 18:45:00")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert!(filtered.is_empty());
    }

    #[test]
    fn clips_pause_that_straddles_workday_start() {
        let wd = workday("2026-07-29 10:00:00", Some("2026-07-29 18:00:00"));
        let pauses = vec![pause(1, "2026-07-29 09:50:00", "2026-07-29 10:10:00")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert_eq!(filtered.len(), 1);
        assert_eq!(
            filtered[0].start,
            NaiveDateTime::parse_from_str("2026-07-29 10:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
        );
        assert_eq!(
            filtered[0].end.unwrap(),
            NaiveDateTime::parse_from_str("2026-07-29 10:10:00", "%Y-%m-%d %H:%M:%S").unwrap()
        );
        assert_eq!(filtered[0].duration.unwrap().num_minutes(), 10);
    }

    #[test]
    fn keeps_pause_fully_inside_workday() {
        let wd = workday("2026-07-29 10:00:00", Some("2026-07-29 18:00:00"));
        let pauses = vec![pause(1, "2026-07-29 12:00:00", "2026-07-29 12:20:00")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].duration.unwrap().num_minutes(), 20);
    }
}