kaccy-db 0.2.0

Database layer for Kaccy Protocol - PostgreSQL, Redis, and distributed caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! Commitment repository

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use sqlx::PgPool;
use uuid::Uuid;

use crate::error::Result;
use crate::helpers::calculate_offset;

/// Output commitment data from database
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct CommitmentRow {
    /// Unique identifier for the commitment.
    pub commitment_id: Uuid,
    /// User who made the commitment.
    pub user_id: Uuid,
    /// Token associated with the commitment.
    pub token_id: Uuid,
    /// Short title describing the commitment.
    pub title: String,
    /// Optional detailed description of the commitment.
    pub description: Option<String>,
    /// Deadline by which the commitment must be fulfilled.
    pub deadline: DateTime<Utc>,
    /// Current status (e.g., pending, completed, verified, failed).
    pub status: String,
    /// URL to submitted evidence, if any.
    pub evidence_url: Option<String>,
    /// Description of the submitted evidence.
    pub evidence_description: Option<String>,
    /// Timestamp when the commitment was verified, if verified.
    pub verified_at: Option<DateTime<Utc>>,
    /// User ID of the verifier, if verified.
    pub verified_by: Option<Uuid>,
    /// Timestamp when the commitment was created.
    pub created_at: DateTime<Utc>,
}

/// Commitment with user and token details
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct CommitmentWithDetails {
    /// Unique identifier for the commitment.
    pub commitment_id: Uuid,
    /// User who made the commitment.
    pub user_id: Uuid,
    /// Token associated with the commitment.
    pub token_id: Uuid,
    /// Short title describing the commitment.
    pub title: String,
    /// Optional detailed description.
    pub description: Option<String>,
    /// Deadline for fulfillment.
    pub deadline: DateTime<Utc>,
    /// Current status string.
    pub status: String,
    /// URL to submitted evidence.
    pub evidence_url: Option<String>,
    /// Description of the evidence.
    pub evidence_description: Option<String>,
    /// Timestamp when verified.
    pub verified_at: Option<DateTime<Utc>>,
    /// User ID of the verifier.
    pub verified_by: Option<Uuid>,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
    // User details
    /// Username of the commitment author.
    pub username: String,
    /// Display name of the commitment author.
    pub display_name: Option<String>,
    /// Reputation score of the commitment author.
    pub reputation_score: rust_decimal::Decimal,
    // Token details
    /// Trading symbol of the associated token.
    pub token_symbol: String,
    /// Full name of the associated token.
    pub token_name: String,
}

/// Commitment statistics for a user
#[derive(Debug, Clone)]
pub struct CommitmentStats {
    /// User these statistics belong to.
    pub user_id: Uuid,
    /// Total number of commitments made.
    pub total_commitments: i64,
    /// Number of commitments still pending.
    pub pending_count: i64,
    /// Number of commitments marked as completed.
    pub completed_count: i64,
    /// Number of commitments that have been verified.
    pub verified_count: i64,
    /// Number of commitments that failed.
    pub failed_count: i64,
    /// Number of commitments that expired before completion.
    pub expired_count: i64,
    /// Ratio of verified to total (0.0–1.0).
    pub fulfillment_rate: f64,
}

/// Repository for commitment operations
pub struct CommitmentRepository {
    pool: PgPool,
}

impl CommitmentRepository {
    /// Create a new commitment repository.
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    /// Create a new commitment
    pub async fn create(
        &self,
        user_id: Uuid,
        token_id: Uuid,
        title: &str,
        description: Option<&str>,
        deadline: DateTime<Utc>,
    ) -> Result<CommitmentRow> {
        let commitment = sqlx::query_as::<_, CommitmentRow>(
            r#"
            INSERT INTO output_commitments (user_id, token_id, title, description, deadline)
            VALUES ($1, $2, $3, $4, $5)
            RETURNING *
            "#,
        )
        .bind(user_id)
        .bind(token_id)
        .bind(title)
        .bind(description)
        .bind(deadline)
        .fetch_one(&self.pool)
        .await?;

        Ok(commitment)
    }

    /// Find commitment by ID
    pub async fn find_by_id(&self, commitment_id: Uuid) -> Result<Option<CommitmentRow>> {
        let commitment = sqlx::query_as::<_, CommitmentRow>(
            r#"SELECT * FROM output_commitments WHERE commitment_id = $1"#,
        )
        .bind(commitment_id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(commitment)
    }

    /// Find commitment with user and token details
    pub async fn find_by_id_with_details(
        &self,
        commitment_id: Uuid,
    ) -> Result<Option<CommitmentWithDetails>> {
        let commitment = sqlx::query_as::<_, CommitmentWithDetails>(
            r#"
            SELECT
                c.*,
                u.username,
                u.display_name,
                u.reputation_score,
                t.symbol as token_symbol,
                t.name as token_name
            FROM output_commitments c
            JOIN users u ON c.user_id = u.user_id
            JOIN tokens t ON c.token_id = t.token_id
            WHERE c.commitment_id = $1
            "#,
        )
        .bind(commitment_id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(commitment)
    }

    /// Update commitment with evidence
    pub async fn submit_evidence(
        &self,
        commitment_id: Uuid,
        user_id: Uuid,
        evidence_url: &str,
        evidence_description: Option<&str>,
    ) -> Result<Option<CommitmentRow>> {
        let commitment = sqlx::query_as::<_, CommitmentRow>(
            r#"
            UPDATE output_commitments
            SET evidence_url = $3, evidence_description = $4, status = 'completed'
            WHERE commitment_id = $1 AND user_id = $2 AND status = 'pending'
            RETURNING *
            "#,
        )
        .bind(commitment_id)
        .bind(user_id)
        .bind(evidence_url)
        .bind(evidence_description)
        .fetch_optional(&self.pool)
        .await?;

        Ok(commitment)
    }

    /// Mark commitment as verified
    pub async fn mark_verified(
        &self,
        commitment_id: Uuid,
        verified_by: Uuid,
    ) -> Result<Option<CommitmentRow>> {
        let commitment = sqlx::query_as::<_, CommitmentRow>(
            r#"
            UPDATE output_commitments
            SET status = 'verified', verified_at = NOW(), verified_by = $2
            WHERE commitment_id = $1 AND status = 'completed'
            RETURNING *
            "#,
        )
        .bind(commitment_id)
        .bind(verified_by)
        .fetch_optional(&self.pool)
        .await?;

        Ok(commitment)
    }

    /// Mark commitment as failed
    pub async fn mark_failed(
        &self,
        commitment_id: Uuid,
        verified_by: Uuid,
    ) -> Result<Option<CommitmentRow>> {
        let commitment = sqlx::query_as::<_, CommitmentRow>(
            r#"
            UPDATE output_commitments
            SET status = 'failed', verified_at = NOW(), verified_by = $2
            WHERE commitment_id = $1 AND status = 'completed'
            RETURNING *
            "#,
        )
        .bind(commitment_id)
        .bind(verified_by)
        .fetch_optional(&self.pool)
        .await?;

        Ok(commitment)
    }

    /// Get user's commitments with pagination
    pub async fn get_user_commitments(
        &self,
        user_id: Uuid,
        page: u32,
        limit: u32,
    ) -> Result<Vec<CommitmentRow>> {
        let offset = calculate_offset(page, limit);

        let commitments = sqlx::query_as::<_, CommitmentRow>(
            r#"
            SELECT * FROM output_commitments
            WHERE user_id = $1
            ORDER BY created_at DESC
            LIMIT $2 OFFSET $3
            "#,
        )
        .bind(user_id)
        .bind(limit as i64)
        .bind(offset)
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Get user's commitments filtered by status
    pub async fn get_user_commitments_by_status(
        &self,
        user_id: Uuid,
        status: &str,
        limit: u32,
    ) -> Result<Vec<CommitmentRow>> {
        let commitments = sqlx::query_as::<_, CommitmentRow>(
            r#"
            SELECT * FROM output_commitments
            WHERE user_id = $1 AND status = $2
            ORDER BY created_at DESC
            LIMIT $3
            "#,
        )
        .bind(user_id)
        .bind(status)
        .bind(limit as i64)
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Get token's commitments
    pub async fn get_token_commitments(
        &self,
        token_id: Uuid,
        page: u32,
        limit: u32,
    ) -> Result<Vec<CommitmentRow>> {
        let offset = calculate_offset(page, limit);

        let commitments = sqlx::query_as::<_, CommitmentRow>(
            r#"
            SELECT * FROM output_commitments
            WHERE token_id = $1
            ORDER BY created_at DESC
            LIMIT $2 OFFSET $3
            "#,
        )
        .bind(token_id)
        .bind(limit as i64)
        .bind(offset)
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Get pending commitments for verification (with details)
    pub async fn get_pending_verification(&self, limit: u32) -> Result<Vec<CommitmentWithDetails>> {
        let commitments = sqlx::query_as::<_, CommitmentWithDetails>(
            r#"
            SELECT
                c.*,
                u.username,
                u.display_name,
                u.reputation_score,
                t.symbol as token_symbol,
                t.name as token_name
            FROM output_commitments c
            JOIN users u ON c.user_id = u.user_id
            JOIN tokens t ON c.token_id = t.token_id
            WHERE c.status = 'completed'
            ORDER BY c.created_at ASC
            LIMIT $1
            "#,
        )
        .bind(limit as i64)
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Get overdue commitments that need to be expired
    pub async fn get_overdue_commitments(&self) -> Result<Vec<CommitmentRow>> {
        let commitments = sqlx::query_as::<_, CommitmentRow>(
            r#"
            SELECT * FROM output_commitments
            WHERE status = 'pending' AND deadline < NOW()
            ORDER BY deadline ASC
            "#,
        )
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Expire a single commitment
    pub async fn expire(&self, commitment_id: Uuid) -> Result<Option<CommitmentRow>> {
        let commitment = sqlx::query_as::<_, CommitmentRow>(
            r#"
            UPDATE output_commitments
            SET status = 'expired'
            WHERE commitment_id = $1 AND status = 'pending'
            RETURNING *
            "#,
        )
        .bind(commitment_id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(commitment)
    }

    /// Get commitment statistics for a user
    pub async fn get_user_stats(&self, user_id: Uuid) -> Result<CommitmentStats> {
        let row: (i64, i64, i64, i64, i64, i64) = sqlx::query_as(
            r#"
            SELECT
                COUNT(*) as total,
                COUNT(*) FILTER (WHERE status = 'pending') as pending,
                COUNT(*) FILTER (WHERE status = 'completed') as completed,
                COUNT(*) FILTER (WHERE status = 'verified') as verified,
                COUNT(*) FILTER (WHERE status = 'failed') as failed,
                COUNT(*) FILTER (WHERE status = 'expired') as expired
            FROM output_commitments
            WHERE user_id = $1
            "#,
        )
        .bind(user_id)
        .fetch_one(&self.pool)
        .await?;

        let total_resolved = row.3 + row.4; // verified + failed
        let fulfillment_rate = if total_resolved > 0 {
            row.3 as f64 / total_resolved as f64
        } else {
            0.0
        };

        Ok(CommitmentStats {
            user_id,
            total_commitments: row.0,
            pending_count: row.1,
            completed_count: row.2,
            verified_count: row.3,
            failed_count: row.4,
            expired_count: row.5,
            fulfillment_rate,
        })
    }

    /// Count pending verification queue
    pub async fn count_pending_verification(&self) -> Result<i64> {
        let (count,): (i64,) =
            sqlx::query_as(r#"SELECT COUNT(*) FROM output_commitments WHERE status = 'completed'"#)
                .fetch_one(&self.pool)
                .await?;

        Ok(count)
    }

    /// Get commitments approaching deadline (for notifications)
    pub async fn get_approaching_deadline(&self, hours_before: i64) -> Result<Vec<CommitmentRow>> {
        let commitments = sqlx::query_as::<_, CommitmentRow>(
            r#"
            SELECT * FROM output_commitments
            WHERE status = 'pending'
              AND deadline > NOW()
              AND deadline < NOW() + INTERVAL '1 hour' * $1
            ORDER BY deadline ASC
            "#,
        )
        .bind(hours_before)
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Batch expire overdue commitments
    pub async fn batch_expire_overdue(&self) -> Result<u64> {
        let result = sqlx::query(
            r#"
            UPDATE output_commitments
            SET status = 'expired'
            WHERE status = 'pending' AND deadline < NOW()
            "#,
        )
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }

    /// Batch verify multiple commitments
    pub async fn batch_verify(&self, commitment_ids: &[Uuid], verified_by: Uuid) -> Result<u64> {
        let result = sqlx::query(
            r#"
            UPDATE output_commitments
            SET status = 'verified', verified_at = NOW(), verified_by = $2
            WHERE commitment_id = ANY($1) AND status = 'completed'
            "#,
        )
        .bind(commitment_ids)
        .bind(verified_by)
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }

    /// Batch mark multiple commitments as failed
    pub async fn batch_mark_failed(
        &self,
        commitment_ids: &[Uuid],
        verified_by: Uuid,
    ) -> Result<u64> {
        let result = sqlx::query(
            r#"
            UPDATE output_commitments
            SET status = 'failed', verified_at = NOW(), verified_by = $2
            WHERE commitment_id = ANY($1) AND status = 'completed'
            "#,
        )
        .bind(commitment_ids)
        .bind(verified_by)
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }

    /// Get commitment statistics for a token
    pub async fn get_token_stats(&self, token_id: Uuid) -> Result<TokenCommitmentStats> {
        let row: (i64, i64, i64, i64, i64, i64) = sqlx::query_as(
            r#"
            SELECT
                COUNT(*) as total,
                COUNT(*) FILTER (WHERE status = 'pending') as pending,
                COUNT(*) FILTER (WHERE status = 'completed') as completed,
                COUNT(*) FILTER (WHERE status = 'verified') as verified,
                COUNT(*) FILTER (WHERE status = 'failed') as failed,
                COUNT(*) FILTER (WHERE status = 'expired') as expired
            FROM output_commitments
            WHERE token_id = $1
            "#,
        )
        .bind(token_id)
        .fetch_one(&self.pool)
        .await?;

        let total_resolved = row.3 + row.4; // verified + failed
        let fulfillment_rate = if total_resolved > 0 {
            row.3 as f64 / total_resolved as f64
        } else {
            0.0
        };

        Ok(TokenCommitmentStats {
            token_id,
            total_commitments: row.0,
            pending_count: row.1,
            completed_count: row.2,
            verified_count: row.3,
            failed_count: row.4,
            expired_count: row.5,
            fulfillment_rate,
        })
    }

    /// Get top performers by fulfillment rate (minimum commitments required)
    pub async fn get_top_performers(
        &self,
        min_commitments: i64,
        limit: i64,
    ) -> Result<Vec<UserPerformance>> {
        let performers = sqlx::query_as::<_, UserPerformance>(
            r#"
            SELECT
                c.user_id,
                u.username,
                u.display_name,
                u.reputation_score,
                COUNT(*) as total_commitments,
                COUNT(*) FILTER (WHERE c.status = 'verified') as verified_count,
                COUNT(*) FILTER (WHERE c.status = 'failed') as failed_count,
                CASE
                    WHEN COUNT(*) FILTER (WHERE c.status IN ('verified', 'failed')) > 0
                    THEN CAST(COUNT(*) FILTER (WHERE c.status = 'verified') AS DOUBLE PRECISION) /
                         CAST(COUNT(*) FILTER (WHERE c.status IN ('verified', 'failed')) AS DOUBLE PRECISION)
                    ELSE 0.0
                END as fulfillment_rate
            FROM output_commitments c
            JOIN users u ON c.user_id = u.user_id
            GROUP BY c.user_id, u.username, u.display_name, u.reputation_score
            HAVING COUNT(*) >= $1
            ORDER BY fulfillment_rate DESC, verified_count DESC
            LIMIT $2
            "#,
        )
        .bind(min_commitments)
        .bind(limit)
        .fetch_all(&self.pool)
        .await?;

        Ok(performers)
    }

    /// Get average time to complete commitments (in hours)
    pub async fn get_average_completion_time(&self, user_id: Option<Uuid>) -> Result<Option<f64>> {
        let row: (Option<f64>,) = if let Some(uid) = user_id {
            sqlx::query_as(
                r#"
                SELECT AVG(EXTRACT(EPOCH FROM (verified_at - created_at)) / 3600.0)
                FROM output_commitments
                WHERE user_id = $1 AND status IN ('verified', 'failed')
                "#,
            )
            .bind(uid)
            .fetch_one(&self.pool)
            .await?
        } else {
            sqlx::query_as(
                r#"
                SELECT AVG(EXTRACT(EPOCH FROM (verified_at - created_at)) / 3600.0)
                FROM output_commitments
                WHERE status IN ('verified', 'failed')
                "#,
            )
            .fetch_one(&self.pool)
            .await?
        };

        Ok(row.0)
    }

    /// Get average verification turnaround time (time from completed to verified/failed, in hours)
    pub async fn get_average_verification_time(&self) -> Result<Option<f64>> {
        let row: (Option<f64>,) = sqlx::query_as(
            r#"
            SELECT AVG(EXTRACT(EPOCH FROM (verified_at - updated_at)) / 3600.0)
            FROM output_commitments
            WHERE status IN ('verified', 'failed') AND verified_at IS NOT NULL
            "#,
        )
        .fetch_one(&self.pool)
        .await?;

        Ok(row.0)
    }

    /// Get commitments by date range
    pub async fn get_by_date_range(
        &self,
        start_date: DateTime<Utc>,
        end_date: DateTime<Utc>,
        limit: i64,
        offset: i64,
    ) -> Result<Vec<CommitmentRow>> {
        let commitments = sqlx::query_as::<_, CommitmentRow>(
            r#"
            SELECT * FROM output_commitments
            WHERE created_at BETWEEN $1 AND $2
            ORDER BY created_at DESC
            LIMIT $3 OFFSET $4
            "#,
        )
        .bind(start_date)
        .bind(end_date)
        .bind(limit)
        .bind(offset)
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Get commitments by deadline range
    pub async fn get_by_deadline_range(
        &self,
        start_deadline: DateTime<Utc>,
        end_deadline: DateTime<Utc>,
        status: Option<&str>,
        limit: i64,
    ) -> Result<Vec<CommitmentRow>> {
        let commitments = if let Some(s) = status {
            sqlx::query_as::<_, CommitmentRow>(
                r#"
                SELECT * FROM output_commitments
                WHERE deadline BETWEEN $1 AND $2 AND status = $3
                ORDER BY deadline ASC
                LIMIT $4
                "#,
            )
            .bind(start_deadline)
            .bind(end_deadline)
            .bind(s)
            .bind(limit)
            .fetch_all(&self.pool)
            .await?
        } else {
            sqlx::query_as::<_, CommitmentRow>(
                r#"
                SELECT * FROM output_commitments
                WHERE deadline BETWEEN $1 AND $2
                ORDER BY deadline ASC
                LIMIT $3
                "#,
            )
            .bind(start_deadline)
            .bind(end_deadline)
            .bind(limit)
            .fetch_all(&self.pool)
            .await?
        };

        Ok(commitments)
    }

    /// Search commitments by title (case-insensitive)
    pub async fn search_by_title(
        &self,
        search_term: &str,
        limit: i64,
        offset: i64,
    ) -> Result<Vec<CommitmentRow>> {
        let search_pattern = format!("%{}%", search_term);
        let commitments = sqlx::query_as::<_, CommitmentRow>(
            r#"
            SELECT * FROM output_commitments
            WHERE LOWER(title) LIKE LOWER($1)
            ORDER BY created_at DESC
            LIMIT $2 OFFSET $3
            "#,
        )
        .bind(search_pattern)
        .bind(limit)
        .bind(offset)
        .fetch_all(&self.pool)
        .await?;

        Ok(commitments)
    }

    /// Get commitment trends (count by status over time period)
    pub async fn get_trends(
        &self,
        start_date: DateTime<Utc>,
        end_date: DateTime<Utc>,
    ) -> Result<Vec<CommitmentTrend>> {
        let trends = sqlx::query_as::<_, CommitmentTrend>(
            r#"
            SELECT
                DATE(created_at) as date,
                COUNT(*) as total,
                COUNT(*) FILTER (WHERE status = 'pending') as pending,
                COUNT(*) FILTER (WHERE status = 'completed') as completed,
                COUNT(*) FILTER (WHERE status = 'verified') as verified,
                COUNT(*) FILTER (WHERE status = 'failed') as failed,
                COUNT(*) FILTER (WHERE status = 'expired') as expired
            FROM output_commitments
            WHERE created_at BETWEEN $1 AND $2
            GROUP BY DATE(created_at)
            ORDER BY DATE(created_at) ASC
            "#,
        )
        .bind(start_date)
        .bind(end_date)
        .fetch_all(&self.pool)
        .await?;

        Ok(trends)
    }

    /// Count commitments by status
    pub async fn count_by_status(&self, status: &str) -> Result<i64> {
        let row: (i64,) = sqlx::query_as(
            r#"
            SELECT COUNT(*) FROM output_commitments WHERE status = $1
            "#,
        )
        .bind(status)
        .fetch_one(&self.pool)
        .await?;

        Ok(row.0)
    }

    /// Delete old expired commitments (data retention policy)
    pub async fn cleanup_expired(&self, days_old: i64) -> Result<u64> {
        let result = sqlx::query(
            r#"
            DELETE FROM output_commitments
            WHERE status = 'expired'
            AND created_at < NOW() - INTERVAL '1 day' * $1
            "#,
        )
        .bind(days_old)
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }
}

/// Token commitment statistics
#[derive(Debug, Clone)]
pub struct TokenCommitmentStats {
    /// Token these statistics belong to.
    pub token_id: Uuid,
    /// Total commitments involving this token.
    pub total_commitments: i64,
    /// Number of pending commitments.
    pub pending_count: i64,
    /// Number of completed commitments.
    pub completed_count: i64,
    /// Number of verified commitments.
    pub verified_count: i64,
    /// Number of failed commitments.
    pub failed_count: i64,
    /// Number of expired commitments.
    pub expired_count: i64,
    /// Ratio of verified to total (0.0–1.0).
    pub fulfillment_rate: f64,
}

/// User performance metrics
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct UserPerformance {
    /// Unique identifier of the user.
    pub user_id: Uuid,
    /// Username of the user.
    pub username: String,
    /// Display name of the user.
    pub display_name: Option<String>,
    /// Current reputation score.
    pub reputation_score: Decimal,
    /// Total number of commitments.
    pub total_commitments: i64,
    /// Number of verified commitments.
    pub verified_count: i64,
    /// Number of failed commitments.
    pub failed_count: i64,
    /// Ratio of verified to total (0.0–1.0).
    pub fulfillment_rate: f64,
}

/// Commitment trend data (daily aggregation)
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct CommitmentTrend {
    /// Date of the aggregation bucket.
    pub date: chrono::NaiveDate,
    /// Total commitments for this day.
    pub total: i64,
    /// Pending commitments on this day.
    pub pending: i64,
    /// Completed commitments on this day.
    pub completed: i64,
    /// Verified commitments on this day.
    pub verified: i64,
    /// Failed commitments on this day.
    pub failed: i64,
    /// Expired commitments on this day.
    pub expired: i64,
}

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

    #[test]
    fn test_token_commitment_stats_creation() {
        let stats = TokenCommitmentStats {
            token_id: Uuid::new_v4(),
            total_commitments: 100,
            pending_count: 20,
            completed_count: 30,
            verified_count: 40,
            failed_count: 5,
            expired_count: 5,
            fulfillment_rate: 0.89,
        };

        assert_eq!(stats.total_commitments, 100);
        assert_eq!(stats.verified_count, 40);
        assert_eq!(stats.fulfillment_rate, 0.89);
    }

    #[test]
    fn test_user_performance_creation() {
        let perf = UserPerformance {
            user_id: Uuid::new_v4(),
            username: "testuser".to_string(),
            display_name: Some("Test User".to_string()),
            reputation_score: Decimal::new(850, 0),
            total_commitments: 50,
            verified_count: 45,
            failed_count: 5,
            fulfillment_rate: 0.9,
        };

        assert_eq!(perf.username, "testuser");
        assert_eq!(perf.total_commitments, 50);
        assert_eq!(perf.fulfillment_rate, 0.9);
    }

    #[test]
    fn test_commitment_trend_creation() {
        let trend = CommitmentTrend {
            date: chrono::NaiveDate::from_ymd_opt(2026, 1, 18).unwrap(),
            total: 100,
            pending: 30,
            completed: 20,
            verified: 40,
            failed: 5,
            expired: 5,
        };

        assert_eq!(trend.total, 100);
        assert_eq!(trend.verified, 40);
    }

    #[test]
    fn test_fulfillment_rate_calculation() {
        let verified = 90i64;
        let failed = 10i64;
        let total_resolved = verified + failed;

        let rate = if total_resolved > 0 {
            verified as f64 / total_resolved as f64
        } else {
            0.0
        };

        assert_eq!(rate, 0.9);
    }

    #[test]
    fn test_fulfillment_rate_zero_resolved() {
        let verified = 0i64;
        let failed = 0i64;
        let total_resolved = verified + failed;

        let rate = if total_resolved > 0 {
            verified as f64 / total_resolved as f64
        } else {
            0.0
        };

        assert_eq!(rate, 0.0);
    }

    #[test]
    fn test_fulfillment_rate_perfect() {
        let verified = 100i64;
        let failed = 0i64;
        let total_resolved = verified + failed;

        let rate = if total_resolved > 0 {
            verified as f64 / total_resolved as f64
        } else {
            0.0
        };

        assert_eq!(rate, 1.0);
    }

    #[test]
    fn test_commitment_stats_creation() {
        let stats = CommitmentStats {
            user_id: Uuid::new_v4(),
            total_commitments: 100,
            pending_count: 20,
            completed_count: 30,
            verified_count: 40,
            failed_count: 5,
            expired_count: 5,
            fulfillment_rate: 0.89,
        };

        assert_eq!(stats.total_commitments, 100);
        assert_eq!(stats.verified_count, 40);
    }

    #[test]
    fn test_search_pattern_generation() {
        let search_term = "token";
        let pattern = format!("%{}%", search_term);
        assert_eq!(pattern, "%token%");
    }

    #[test]
    fn test_commitment_row_clone() {
        let row = CommitmentRow {
            commitment_id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            token_id: Uuid::new_v4(),
            title: "Test Commitment".to_string(),
            description: Some("Description".to_string()),
            deadline: Utc::now(),
            status: "pending".to_string(),
            evidence_url: None,
            evidence_description: None,
            verified_at: None,
            verified_by: None,
            created_at: Utc::now(),
        };

        let cloned = row.clone();
        assert_eq!(cloned.title, row.title);
        assert_eq!(cloned.status, row.status);
    }

    #[test]
    fn test_commitment_with_details_clone() {
        let details = CommitmentWithDetails {
            commitment_id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            token_id: Uuid::new_v4(),
            title: "Test".to_string(),
            description: None,
            deadline: Utc::now(),
            status: "pending".to_string(),
            evidence_url: None,
            evidence_description: None,
            verified_at: None,
            verified_by: None,
            created_at: Utc::now(),
            username: "testuser".to_string(),
            display_name: Some("Test User".to_string()),
            reputation_score: Decimal::new(800, 0),
            token_symbol: "TEST".to_string(),
            token_name: "Test Token".to_string(),
        };

        let cloned = details.clone();
        assert_eq!(cloned.username, details.username);
        assert_eq!(cloned.token_symbol, details.token_symbol);
    }
}