stateset-db 1.22.0

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

use super::parse_helpers::{parse_decimal, parse_uuid};
use super::{
    build_in_clause, map_db_error, params_refs, parse_datetime_row, parse_decimal_opt_row,
    parse_decimal_row, parse_enum_row, parse_uuid_row, sum_decimal_query, uuid_params,
};
use chrono::Utc;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rust_decimal::Decimal;
use stateset_core::{
    BatchResult, CommerceError, CreateReturn, CustomerId, OrderId, OrderItemId, Result, Return,
    ReturnFilter, ReturnId, ReturnItem, ReturnRepository, ReturnStatus, UpdateReturn,
    validate_batch_size,
};
use uuid::Uuid;

/// SQLite implementation of `ReturnRepository`
#[derive(Debug)]
pub struct SqliteReturnRepository {
    pool: Pool<SqliteConnectionManager>,
}

/// Validate a single return line against its order item, inside a write
/// transaction, returning the item's `(sku, name, unit_price)` for the caller
/// to record on the return.
///
/// Rejects the return when:
/// - the order item does not exist,
/// - the order item belongs to a different order than the one being returned, or
/// - returning `return_qty` more units would exceed what was purchased, counting
///   units already claimed by non-terminal returns (rejected/cancelled returns
///   release their claim).
///
/// This guards against over-returning (and thus over-refunding) more units than
/// were ordered, and against returning another order's items.
fn validate_return_item_tx(
    tx: &rusqlite::Transaction<'_>,
    order_id: &str,
    order_item_id: &str,
    return_qty: i64,
) -> Result<(String, String, String)> {
    let (sku, name, unit_price, oi_order_id, ordered_qty): (String, String, String, String, i64) =
        tx.query_row(
            "SELECT sku, name, unit_price, order_id, quantity FROM order_items WHERE id = ?",
            [order_item_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),
        )
        .map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                CommerceError::ValidationError(format!("Order item {order_item_id} not found"))
            }
            other => map_db_error(other),
        })?;

    if oi_order_id != order_id {
        return Err(CommerceError::ValidationError(format!(
            "Order item {order_item_id} does not belong to order {order_id}"
        )));
    }

    // Units already returned for this order item, excluding rejected/cancelled
    // returns (which release their claim on the ordered quantity).
    let already_returned: i64 = tx
        .query_row(
            "SELECT COALESCE(SUM(ri.quantity), 0) FROM return_items ri
             JOIN returns r ON ri.return_id = r.id
             WHERE ri.order_item_id = ? AND r.status NOT IN ('rejected', 'cancelled')",
            [order_item_id],
            |row| row.get(0),
        )
        .map_err(map_db_error)?;

    if return_qty + already_returned > ordered_qty {
        return Err(CommerceError::ValidationError(format!(
            "Cannot return {return_qty} of order item {order_item_id}: only {} remain returnable ({ordered_qty} ordered, {already_returned} already returned)",
            ordered_qty - already_returned
        )));
    }

    Ok((sku, name, unit_price))
}

impl SqliteReturnRepository {
    #[must_use]
    pub const fn new(pool: Pool<SqliteConnectionManager>) -> Self {
        Self { pool }
    }

    fn conn(&self) -> Result<r2d2::PooledConnection<SqliteConnectionManager>> {
        self.pool.get().map_err(|e| CommerceError::DatabaseError(e.to_string()))
    }

    fn row_to_return(row: &rusqlite::Row<'_>) -> rusqlite::Result<Return> {
        Ok(Return {
            id: ReturnId::from(parse_uuid_row(&row.get::<_, String>("id")?, "return", "id")?),
            order_id: OrderId::from(parse_uuid_row(
                &row.get::<_, String>("order_id")?,
                "return",
                "order_id",
            )?),
            customer_id: CustomerId::from(parse_uuid_row(
                &row.get::<_, String>("customer_id")?,
                "return",
                "customer_id",
            )?),
            status: parse_enum_row(&row.get::<_, String>("status")?, "return", "status")?,
            reason: parse_enum_row(&row.get::<_, String>("reason")?, "return", "reason")?,
            reason_details: row.get("reason_details")?,
            idempotency_key: row.get("idempotency_key")?,
            refund_amount: parse_decimal_opt_row(
                row.get::<_, Option<String>>("refund_amount")?,
                "return",
                "refund_amount",
            )?,
            refund_method: row.get("refund_method")?,
            tracking_number: row.get("tracking_number")?,
            items: vec![], // Loaded separately
            notes: row.get("notes")?,
            version: row.get::<_, Option<i32>>("version")?.unwrap_or(1),
            created_at: parse_datetime_row(
                &row.get::<_, String>("created_at")?,
                "return",
                "created_at",
            )?,
            updated_at: parse_datetime_row(
                &row.get::<_, String>("updated_at")?,
                "return",
                "updated_at",
            )?,
        })
    }

    /// Load items for many returns in one batched `IN (...)` query, keyed by
    /// the return id's string form.
    fn load_return_items_batch(
        conn: &rusqlite::Connection,
        ids: &[ReturnId],
    ) -> Result<std::collections::HashMap<String, Vec<ReturnItem>>> {
        let mut items_by_id: std::collections::HashMap<String, Vec<ReturnItem>> =
            std::collections::HashMap::with_capacity(ids.len());
        if ids.is_empty() {
            return Ok(items_by_id);
        }
        let placeholders = vec!["?"; ids.len()].join(", ");
        let sql = format!(
            "SELECT id, return_id, order_item_id, sku, name, quantity, condition, refund_amount
             FROM return_items WHERE return_id IN ({placeholders})"
        );
        let mut stmt = conn.prepare(&sql).map_err(map_db_error)?;
        let params = ids.iter().map(ToString::to_string).collect::<Vec<_>>();
        let items = stmt
            .query_map(rusqlite::params_from_iter(params.iter()), |row| {
                Ok(ReturnItem {
                    id: parse_uuid_row(&row.get::<_, String>("id")?, "return_item", "id")?,
                    return_id: ReturnId::from(parse_uuid_row(
                        &row.get::<_, String>("return_id")?,
                        "return_item",
                        "return_id",
                    )?),
                    order_item_id: OrderItemId::from(parse_uuid_row(
                        &row.get::<_, String>("order_item_id")?,
                        "return_item",
                        "order_item_id",
                    )?),
                    sku: row.get("sku")?,
                    name: row.get("name")?,
                    quantity: row.get("quantity")?,
                    condition: parse_enum_row(
                        &row.get::<_, String>("condition")?,
                        "return_item",
                        "condition",
                    )?,
                    refund_amount: parse_decimal_row(
                        &row.get::<_, String>("refund_amount")?,
                        "return_item",
                        "refund_amount",
                    )?,
                })
            })
            .map_err(map_db_error)?
            .collect::<rusqlite::Result<Vec<_>>>()
            .map_err(map_db_error)?;
        for item in items {
            items_by_id.entry(item.return_id.to_string()).or_default().push(item);
        }
        Ok(items_by_id)
    }

    #[allow(dead_code)]
    fn load_return_items(&self, return_id: Uuid) -> Result<Vec<ReturnItem>> {
        let conn = self.conn()?;
        let mut stmt = conn
            .prepare(
                "SELECT id, return_id, order_item_id, sku, name, quantity, condition, refund_amount
                 FROM return_items WHERE return_id = ?",
            )
            .map_err(map_db_error)?;

        let items = stmt
            .query_map([return_id.to_string()], |row| {
                Ok(ReturnItem {
                    id: parse_uuid_row(&row.get::<_, String>("id")?, "return_item", "id")?,
                    return_id: ReturnId::from(parse_uuid_row(
                        &row.get::<_, String>("return_id")?,
                        "return_item",
                        "return_id",
                    )?),
                    order_item_id: OrderItemId::from(parse_uuid_row(
                        &row.get::<_, String>("order_item_id")?,
                        "return_item",
                        "order_item_id",
                    )?),
                    sku: row.get("sku")?,
                    name: row.get("name")?,
                    quantity: row.get("quantity")?,
                    condition: parse_enum_row(
                        &row.get::<_, String>("condition")?,
                        "return_item",
                        "condition",
                    )?,
                    refund_amount: parse_decimal_row(
                        &row.get::<_, String>("refund_amount")?,
                        "return_item",
                        "refund_amount",
                    )?,
                })
            })
            .map_err(map_db_error)?
            .collect::<rusqlite::Result<Vec<_>>>()
            .map_err(map_db_error)?;

        Ok(items)
    }

    /// Delete a return and its items
    fn delete(&self, id: Uuid) -> Result<()> {
        let mut conn = self.conn()?;
        let tx = super::begin_immediate(&mut conn).map_err(map_db_error)?;

        tx.execute("DELETE FROM return_items WHERE return_id = ?", [id.to_string()])
            .map_err(map_db_error)?;
        tx.execute("DELETE FROM returns WHERE id = ?", [id.to_string()]).map_err(map_db_error)?;
        tx.commit().map_err(map_db_error)?;
        Ok(())
    }

    fn get_by_idempotency_key(&self, key: &str) -> Result<Option<Return>> {
        let conn = self.conn()?;
        let result = conn.query_row(
            "SELECT * FROM returns WHERE idempotency_key = ?",
            [key],
            Self::row_to_return,
        );

        match result {
            Ok(mut ret) => {
                let mut stmt = conn
                    .prepare(
                        "SELECT id, return_id, order_item_id, sku, name, quantity, condition, refund_amount
                         FROM return_items WHERE return_id = ?",
                    )
                    .map_err(map_db_error)?;

                ret.items = stmt
                    .query_map([ret.id.to_string()], |row| {
                        Ok(ReturnItem {
                            id: parse_uuid_row(&row.get::<_, String>("id")?, "return_item", "id")?,
                            return_id: ReturnId::from(parse_uuid_row(
                                &row.get::<_, String>("return_id")?,
                                "return_item",
                                "return_id",
                            )?),
                            order_item_id: OrderItemId::from(parse_uuid_row(
                                &row.get::<_, String>("order_item_id")?,
                                "return_item",
                                "order_item_id",
                            )?),
                            sku: row.get("sku")?,
                            name: row.get("name")?,
                            quantity: row.get("quantity")?,
                            condition: parse_enum_row(
                                &row.get::<_, String>("condition")?,
                                "return_item",
                                "condition",
                            )?,
                            refund_amount: parse_decimal_row(
                                &row.get::<_, String>("refund_amount")?,
                                "return_item",
                                "refund_amount",
                            )?,
                        })
                    })
                    .map_err(map_db_error)?
                    .collect::<rusqlite::Result<Vec<_>>>()
                    .map_err(map_db_error)?;

                Ok(Some(ret))
            }
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(map_db_error(e)),
        }
    }
}

impl ReturnRepository for SqliteReturnRepository {
    fn create(&self, input: CreateReturn) -> Result<Return> {
        if let Some(key) = input.idempotency_key.as_deref() {
            if let Some(existing) = self.get_by_idempotency_key(key)? {
                return Ok(existing);
            }
        }

        // Validate return has at least one item
        if input.items.is_empty() {
            return Err(CommerceError::ValidationError(
                "Return must have at least one item".into(),
            ));
        }

        // Validate item quantities
        for item in &input.items {
            if item.quantity <= 0 {
                return Err(CommerceError::ValidationError(format!(
                    "Return item quantity must be positive, got {}",
                    item.quantity
                )));
            }
        }

        let mut conn = self.conn()?;
        let tx = super::begin_immediate(&mut conn).map_err(map_db_error)?;
        let id = Uuid::new_v4();
        let now = Utc::now();

        // Get order to get customer_id
        let customer_id: String = tx
            .query_row(
                "SELECT customer_id FROM orders WHERE id = ?",
                [input.order_id.to_string()],
                |row| row.get(0),
            )
            .map_err(|_| CommerceError::OrderNotFound(input.order_id.into()))?;

        tx.execute(
            "INSERT INTO returns (id, order_id, customer_id, status, reason, reason_details, idempotency_key, notes, created_at, updated_at)
             VALUES (?, ?, ?, 'requested', ?, ?, ?, ?, ?, ?)",
            rusqlite::params![
                id.to_string(),
                input.order_id.to_string(),
                customer_id,
                input.reason.to_string(),
                input.reason_details,
                input.idempotency_key,
                input.notes,
                now.to_rfc3339(),
                now.to_rfc3339(),
            ],
        )
        .map_err(map_db_error)?;

        // Insert return items
        for item in &input.items {
            let item_id = Uuid::new_v4();

            // Validate the item belongs to this order and the return quantity
            // does not exceed what remains returnable, then get its details.
            let (sku, name, unit_price) = validate_return_item_tx(
                &tx,
                &input.order_id.to_string(),
                &item.order_item_id.to_string(),
                i64::from(item.quantity),
            )?;

            let refund_amount = parse_decimal(&unit_price, "order_item", "unit_price")?
                * Decimal::from(item.quantity);

            tx.execute(
                "INSERT INTO return_items (id, return_id, order_item_id, sku, name, quantity, condition, refund_amount)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                rusqlite::params![
                    item_id.to_string(),
                    id.to_string(),
                    item.order_item_id.to_string(),
                    sku,
                    name,
                    item.quantity,
                    item.condition.unwrap_or_default().to_string(),
                    refund_amount.to_string(),
                ],
            )
            .map_err(map_db_error)?;
        }

        // Calculate total refund amount
        let return_id_param = id.to_string();
        let return_params: [&dyn rusqlite::ToSql; 1] = [&return_id_param];
        let total_refund = sum_decimal_query(
            &tx,
            "SELECT refund_amount FROM return_items WHERE return_id = ?",
            &return_params,
            "return_item",
            "refund_amount",
        )?;

        tx.execute(
            "UPDATE returns SET refund_amount = ? WHERE id = ?",
            rusqlite::params![total_refund.to_string(), return_id_param],
        )
        .map_err(map_db_error)?;

        // Build the return with items using the same transaction.
        let mut ret = tx
            .query_row("SELECT * FROM returns WHERE id = ?", [id.to_string()], Self::row_to_return)
            .map_err(map_db_error)?;

        {
            let mut stmt = tx
                .prepare(
                    "SELECT id, return_id, order_item_id, sku, name, quantity, condition, refund_amount
                     FROM return_items WHERE return_id = ?",
                )
                .map_err(map_db_error)?;

            ret.items = stmt
                .query_map([id.to_string()], |row| {
                    Ok(ReturnItem {
                        id: parse_uuid_row(&row.get::<_, String>("id")?, "return_item", "id")?,
                        return_id: ReturnId::from(parse_uuid_row(
                            &row.get::<_, String>("return_id")?,
                            "return_item",
                            "return_id",
                        )?),
                        order_item_id: OrderItemId::from(parse_uuid_row(
                            &row.get::<_, String>("order_item_id")?,
                            "return_item",
                            "order_item_id",
                        )?),
                        sku: row.get("sku")?,
                        name: row.get("name")?,
                        quantity: row.get("quantity")?,
                        condition: parse_enum_row(
                            &row.get::<_, String>("condition")?,
                            "return_item",
                            "condition",
                        )?,
                        refund_amount: parse_decimal_row(
                            &row.get::<_, String>("refund_amount")?,
                            "return_item",
                            "refund_amount",
                        )?,
                    })
                })
                .map_err(map_db_error)?
                .collect::<rusqlite::Result<Vec<_>>>()
                .map_err(map_db_error)?;
        }

        tx.commit().map_err(map_db_error)?;

        Ok(ret)
    }

    fn get(&self, id: ReturnId) -> Result<Option<Return>> {
        let conn = self.conn()?;
        let result = conn.query_row(
            "SELECT * FROM returns WHERE id = ?",
            [id.to_string()],
            Self::row_to_return,
        );

        match result {
            Ok(mut ret) => {
                // Inline load_return_items to use same connection
                let mut stmt = conn
                    .prepare(
                        "SELECT id, return_id, order_item_id, sku, name, quantity, condition, refund_amount
                         FROM return_items WHERE return_id = ?",
                    )
                    .map_err(map_db_error)?;

                ret.items = stmt
                    .query_map([id.to_string()], |row| {
                        Ok(ReturnItem {
                            id: parse_uuid_row(&row.get::<_, String>("id")?, "return_item", "id")?,
                            return_id: ReturnId::from(parse_uuid_row(
                                &row.get::<_, String>("return_id")?,
                                "return_item",
                                "return_id",
                            )?),
                            order_item_id: OrderItemId::from(parse_uuid_row(
                                &row.get::<_, String>("order_item_id")?,
                                "return_item",
                                "order_item_id",
                            )?),
                            sku: row.get("sku")?,
                            name: row.get("name")?,
                            quantity: row.get("quantity")?,
                            condition: parse_enum_row(
                                &row.get::<_, String>("condition")?,
                                "return_item",
                                "condition",
                            )?,
                            refund_amount: parse_decimal_row(
                                &row.get::<_, String>("refund_amount")?,
                                "return_item",
                                "refund_amount",
                            )?,
                        })
                    })
                    .map_err(map_db_error)?
                    .collect::<rusqlite::Result<Vec<_>>>()
                    .map_err(map_db_error)?;

                Ok(Some(ret))
            }
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(map_db_error(e)),
        }
    }

    fn update(&self, id: ReturnId, input: UpdateReturn) -> Result<Return> {
        let conn = self.conn()?;
        let now = Utc::now();

        let mut updates = vec!["updated_at = ?", "version = version + 1"];
        let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(now.to_rfc3339())];

        if let Some(status) = &input.status {
            updates.push("status = ?");
            params.push(Box::new(status.to_string()));
        }
        if let Some(tracking) = &input.tracking_number {
            updates.push("tracking_number = ?");
            params.push(Box::new(tracking.clone()));
        }
        if let Some(amount) = &input.refund_amount {
            updates.push("refund_amount = ?");
            params.push(Box::new(amount.to_string()));
        }
        if let Some(method) = &input.refund_method {
            updates.push("refund_method = ?");
            params.push(Box::new(method.clone()));
        }
        if let Some(notes) = &input.notes {
            updates.push("notes = ?");
            params.push(Box::new(notes.clone()));
        }

        params.push(Box::new(id.to_string()));

        let sql = format!("UPDATE returns SET {} WHERE id = ?", updates.join(", "));
        let params_refs: Vec<&dyn rusqlite::ToSql> =
            params.iter().map(std::convert::AsRef::as_ref).collect();

        conn.execute(&sql, params_refs.as_slice()).map_err(map_db_error)?;

        // Inline the get logic to avoid connection pool deadlock
        let result = conn.query_row(
            "SELECT * FROM returns WHERE id = ?",
            [id.to_string()],
            Self::row_to_return,
        );

        let raw_id: Uuid = id.into();
        match result {
            Ok(mut ret) => {
                // Inline load_return_items to use same connection
                let mut stmt = conn
                    .prepare(
                        "SELECT id, return_id, order_item_id, sku, name, quantity, condition, refund_amount
                         FROM return_items WHERE return_id = ?",
                    )
                    .map_err(map_db_error)?;

                ret.items = stmt
                    .query_map([id.to_string()], |row| {
                        Ok(ReturnItem {
                            id: parse_uuid_row(&row.get::<_, String>("id")?, "return_item", "id")?,
                            return_id: ReturnId::from(parse_uuid_row(
                                &row.get::<_, String>("return_id")?,
                                "return_item",
                                "return_id",
                            )?),
                            order_item_id: OrderItemId::from(parse_uuid_row(
                                &row.get::<_, String>("order_item_id")?,
                                "return_item",
                                "order_item_id",
                            )?),
                            sku: row.get("sku")?,
                            name: row.get("name")?,
                            quantity: row.get("quantity")?,
                            condition: parse_enum_row(
                                &row.get::<_, String>("condition")?,
                                "return_item",
                                "condition",
                            )?,
                            refund_amount: parse_decimal_row(
                                &row.get::<_, String>("refund_amount")?,
                                "return_item",
                                "refund_amount",
                            )?,
                        })
                    })
                    .map_err(map_db_error)?
                    .collect::<rusqlite::Result<Vec<_>>>()
                    .map_err(map_db_error)?;

                Ok(ret)
            }
            Err(rusqlite::Error::QueryReturnedNoRows) => Err(CommerceError::ReturnNotFound(raw_id)),
            Err(e) => Err(map_db_error(e)),
        }
    }

    fn list(&self, filter: ReturnFilter) -> Result<Vec<Return>> {
        let conn = self.conn()?;
        let mut sql = "SELECT * FROM returns WHERE 1=1".to_string();
        let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![];

        if let Some(order_id) = &filter.order_id {
            sql.push_str(" AND order_id = ?");
            params.push(Box::new(order_id.to_string()));
        }
        if let Some(customer_id) = &filter.customer_id {
            sql.push_str(" AND customer_id = ?");
            params.push(Box::new(customer_id.to_string()));
        }
        if let Some(status) = &filter.status {
            sql.push_str(" AND status = ?");
            params.push(Box::new(status.to_string()));
        }
        if let Some(reason) = &filter.reason {
            sql.push_str(" AND reason = ?");
            params.push(Box::new(reason.to_string()));
        }
        if let Some(from) = &filter.from_date {
            sql.push_str(" AND created_at >= ?");
            params.push(Box::new(from.to_rfc3339()));
        }
        if let Some(to) = &filter.to_date {
            sql.push_str(" AND created_at <= ?");
            params.push(Box::new(to.to_rfc3339()));
        }

        // Keyset cursor: (created_at, id) for stable DESC ordering
        if let Some((cursor_date, cursor_id)) = &filter.after_cursor {
            sql.push_str(" AND (created_at < ? OR (created_at = ? AND id < ?))");
            params.push(Box::new(cursor_date.clone()));
            params.push(Box::new(cursor_date.clone()));
            params.push(Box::new(cursor_id.clone()));
        }

        sql.push_str(" ORDER BY created_at DESC, id DESC");

        // Offset pagination applies only in non-cursor mode; the helper emits
        // `LIMIT -1 OFFSET n` when an offset is set without a limit (SQLite rejects
        // a bare OFFSET).
        let offset = if filter.after_cursor.is_none() { filter.offset } else { None };
        crate::sqlite::append_limit_offset(&mut sql, filter.limit, offset);

        let params_refs: Vec<&dyn rusqlite::ToSql> =
            params.iter().map(std::convert::AsRef::as_ref).collect();
        let mut stmt = conn.prepare(&sql).map_err(map_db_error)?;

        let returns = stmt
            .query_map(params_refs.as_slice(), Self::row_to_return)
            .map_err(map_db_error)?
            .collect::<rusqlite::Result<Vec<_>>>()
            .map_err(map_db_error)?;

        // Load items for each return using same connection
        let ids: Vec<ReturnId> = returns.iter().map(|r| r.id).collect();
        let mut items_by_id = Self::load_return_items_batch(&conn, &ids)?;
        let mut result = vec![];
        for mut ret in returns {
            ret.items = items_by_id.remove(&ret.id.to_string()).unwrap_or_default();
            result.push(ret);
        }

        Ok(result)
    }

    fn approve(&self, id: ReturnId) -> Result<Return> {
        let ret = self.get(id)?.ok_or(CommerceError::ReturnNotFound(id.into()))?;

        if ret.status != ReturnStatus::Requested {
            return Err(CommerceError::ReturnCannotBeApproved(ret.status.to_string()));
        }

        self.update(id, UpdateReturn { status: Some(ReturnStatus::Approved), ..Default::default() })
    }

    fn reject(&self, id: ReturnId, reason: &str) -> Result<Return> {
        let ret = self.get(id)?.ok_or(CommerceError::ReturnNotFound(id.into()))?;

        if ret.status != ReturnStatus::Requested {
            return Err(CommerceError::ReturnCannotBeApproved(ret.status.to_string()));
        }

        self.update(
            id,
            UpdateReturn {
                status: Some(ReturnStatus::Rejected),
                notes: Some(reason.to_string()),
                ..Default::default()
            },
        )
    }

    fn complete(&self, id: ReturnId) -> Result<Return> {
        let ret = self.get(id)?.ok_or(CommerceError::ReturnNotFound(id.into()))?;

        if !ret.can_complete() {
            return Err(CommerceError::NotPermitted(format!(
                "Return cannot be completed in status: {}",
                ret.status
            )));
        }

        self.update(
            id,
            UpdateReturn { status: Some(ReturnStatus::Completed), ..Default::default() },
        )
    }

    fn cancel(&self, id: ReturnId) -> Result<Return> {
        self.update(
            id,
            UpdateReturn { status: Some(ReturnStatus::Cancelled), ..Default::default() },
        )
    }

    fn count(&self, filter: ReturnFilter) -> Result<u64> {
        let conn = self.conn()?;
        let mut sql = "SELECT COUNT(*) FROM returns WHERE 1=1".to_string();
        let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![];

        if let Some(status) = &filter.status {
            sql.push_str(" AND status = ?");
            params.push(Box::new(status.to_string()));
        }

        let params_refs: Vec<&dyn rusqlite::ToSql> =
            params.iter().map(std::convert::AsRef::as_ref).collect();
        let count: i64 =
            conn.query_row(&sql, params_refs.as_slice(), |row| row.get(0)).map_err(map_db_error)?;

        Ok(count as u64)
    }

    // === Batch Operations ===

    fn create_batch(&self, inputs: Vec<CreateReturn>) -> Result<BatchResult<Return>> {
        validate_batch_size(&inputs)?;
        let mut result = BatchResult::with_capacity(inputs.len());

        for (index, input) in inputs.into_iter().enumerate() {
            match self.create(input) {
                Ok(ret) => result.record_success(ret),
                Err(e) => result.record_failure(index, None, &e),
            }
        }

        Ok(result)
    }

    fn create_batch_atomic(&self, inputs: Vec<CreateReturn>) -> Result<Vec<Return>> {
        validate_batch_size(&inputs)?;
        if inputs.is_empty() {
            return Ok(vec![]);
        }

        let mut conn = self.conn()?;
        let tx = super::begin_immediate(&mut conn).map_err(map_db_error)?;
        let mut results = Vec::with_capacity(inputs.len());

        for input in inputs {
            let id = Uuid::new_v4();
            let now = Utc::now();

            // Get order to get customer_id
            let customer_id: String = tx
                .query_row(
                    "SELECT customer_id FROM orders WHERE id = ?",
                    [input.order_id.to_string()],
                    |row| row.get(0),
                )
                .map_err(|_| CommerceError::OrderNotFound(input.order_id.into()))?;

            tx.execute(
                "INSERT INTO returns (id, order_id, customer_id, status, reason, reason_details, idempotency_key, notes, created_at, updated_at)
                 VALUES (?, ?, ?, 'requested', ?, ?, ?, ?, ?, ?)",
                rusqlite::params![
                    id.to_string(),
                    input.order_id.to_string(),
                    customer_id,
                    input.reason.to_string(),
                    input.reason_details,
                    input.idempotency_key.clone(),
                    input.notes,
                    now.to_rfc3339(),
                    now.to_rfc3339(),
                ],
            )
            .map_err(map_db_error)?;

            // Insert return items
            let mut items = Vec::with_capacity(input.items.len());
            for item in &input.items {
                let item_id = Uuid::new_v4();

                // Validate the item belongs to this order and the return
                // quantity does not exceed what remains returnable, then get its
                // details.
                let (sku, name, unit_price) = validate_return_item_tx(
                    &tx,
                    &input.order_id.to_string(),
                    &item.order_item_id.to_string(),
                    i64::from(item.quantity),
                )?;

                let refund_amount = parse_decimal(&unit_price, "order_item", "unit_price")?
                    * Decimal::from(item.quantity);

                tx.execute(
                    "INSERT INTO return_items (id, return_id, order_item_id, sku, name, quantity, condition, refund_amount)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                    rusqlite::params![
                        item_id.to_string(),
                        id.to_string(),
                        item.order_item_id.to_string(),
                        sku.clone(),
                        name.clone(),
                        item.quantity,
                        item.condition.unwrap_or_default().to_string(),
                        refund_amount.to_string(),
                    ],
                )
                .map_err(map_db_error)?;

                items.push(ReturnItem {
                    id: item_id,
                    return_id: ReturnId::from(id),
                    order_item_id: item.order_item_id,
                    sku,
                    name,
                    quantity: item.quantity,
                    condition: item.condition.unwrap_or_default(),
                    refund_amount,
                });
            }

            // Calculate total refund amount
            let return_id_param = id.to_string();
            let return_params: [&dyn rusqlite::ToSql; 1] = [&return_id_param];
            let total_refund = sum_decimal_query(
                &tx,
                "SELECT refund_amount FROM return_items WHERE return_id = ?",
                &return_params,
                "return_item",
                "refund_amount",
            )?;

            tx.execute(
                "UPDATE returns SET refund_amount = ? WHERE id = ?",
                rusqlite::params![total_refund.to_string(), return_id_param],
            )
            .map_err(map_db_error)?;

            results.push(Return {
                id: ReturnId::from(id),
                order_id: input.order_id,
                customer_id: CustomerId::from(parse_uuid(&customer_id, "return", "customer_id")?),
                status: ReturnStatus::Requested,
                reason: input.reason,
                reason_details: input.reason_details,
                idempotency_key: input.idempotency_key,
                refund_amount: Some(total_refund),
                refund_method: None,
                tracking_number: None,
                items,
                notes: input.notes,
                version: 1,
                created_at: now,
                updated_at: now,
            });
        }

        tx.commit().map_err(map_db_error)?;
        Ok(results)
    }

    fn update_batch(&self, updates: Vec<(ReturnId, UpdateReturn)>) -> Result<BatchResult<Return>> {
        validate_batch_size(&updates)?;
        let mut result = BatchResult::with_capacity(updates.len());

        for (index, (id, input)) in updates.into_iter().enumerate() {
            match self.update(id, input) {
                Ok(ret) => result.record_success(ret),
                Err(e) => result.record_failure(index, Some(id.to_string()), &e),
            }
        }

        Ok(result)
    }

    fn update_batch_atomic(&self, updates: Vec<(ReturnId, UpdateReturn)>) -> Result<Vec<Return>> {
        validate_batch_size(&updates)?;
        if updates.is_empty() {
            return Ok(vec![]);
        }

        let mut conn = self.conn()?;
        let tx = super::begin_immediate(&mut conn).map_err(map_db_error)?;
        let mut results = Vec::with_capacity(updates.len());

        for (id, input) in updates {
            let now = Utc::now();

            let mut update_parts = vec!["updated_at = ?"];
            let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(now.to_rfc3339())];

            if let Some(status) = &input.status {
                update_parts.push("status = ?");
                params.push(Box::new(status.to_string()));
            }
            if let Some(tracking) = &input.tracking_number {
                update_parts.push("tracking_number = ?");
                params.push(Box::new(tracking.clone()));
            }
            if let Some(amount) = &input.refund_amount {
                update_parts.push("refund_amount = ?");
                params.push(Box::new(amount.to_string()));
            }
            if let Some(method) = &input.refund_method {
                update_parts.push("refund_method = ?");
                params.push(Box::new(method.clone()));
            }
            if let Some(notes) = &input.notes {
                update_parts.push("notes = ?");
                params.push(Box::new(notes.clone()));
            }

            params.push(Box::new(id.to_string()));

            let sql = format!("UPDATE returns SET {} WHERE id = ?", update_parts.join(", "));
            let params_refs: Vec<&dyn rusqlite::ToSql> =
                params.iter().map(std::convert::AsRef::as_ref).collect();

            let rows_affected = tx.execute(&sql, params_refs.as_slice()).map_err(map_db_error)?;
            if rows_affected == 0 {
                return Err(CommerceError::ReturnNotFound(id.into()));
            }

            // Fetch the updated return
            let ret = tx
                .query_row(
                    "SELECT * FROM returns WHERE id = ?",
                    [id.to_string()],
                    Self::row_to_return,
                )
                .map_err(map_db_error)?;

            results.push(ret);
        }

        tx.commit().map_err(map_db_error)?;

        // Load items for all returns in one batched query
        let conn = self.conn()?;
        let ids: Vec<ReturnId> = results.iter().map(|r| r.id).collect();
        let mut items_by_id = Self::load_return_items_batch(&conn, &ids)?;
        for ret in &mut results {
            ret.items = items_by_id.remove(&ret.id.to_string()).unwrap_or_default();
        }

        Ok(results)
    }

    fn delete_batch(&self, ids: Vec<ReturnId>) -> Result<BatchResult<Uuid>> {
        validate_batch_size(&ids)?;
        let mut result = BatchResult::with_capacity(ids.len());

        for (index, id) in ids.into_iter().enumerate() {
            let raw_id: Uuid = id.into();
            match self.delete(raw_id) {
                Ok(()) => result.record_success(raw_id),
                Err(e) => result.record_failure(index, Some(id.to_string()), &e),
            }
        }

        Ok(result)
    }

    fn delete_batch_atomic(&self, ids: Vec<ReturnId>) -> Result<()> {
        validate_batch_size(&ids)?;
        if ids.is_empty() {
            return Ok(());
        }

        let mut conn = self.conn()?;
        let tx = super::begin_immediate(&mut conn).map_err(map_db_error)?;

        let raw_ids: Vec<Uuid> = ids.iter().map(|id| (*id).into()).collect();
        let placeholders = build_in_clause(ids.len());
        let params = uuid_params(&raw_ids);
        let params_refs = params_refs(&params);

        // Delete return items first
        let sql = format!("DELETE FROM return_items WHERE return_id IN ({placeholders})");
        tx.execute(&sql, params_refs.as_slice()).map_err(map_db_error)?;

        // Delete returns
        let sql = format!("DELETE FROM returns WHERE id IN ({placeholders})");
        tx.execute(&sql, params_refs.as_slice()).map_err(map_db_error)?;

        tx.commit().map_err(map_db_error)?;
        Ok(())
    }

    fn get_batch(&self, ids: Vec<ReturnId>) -> Result<Vec<Return>> {
        validate_batch_size(&ids)?;
        if ids.is_empty() {
            return Ok(vec![]);
        }

        let conn = self.conn()?;
        let raw_ids: Vec<Uuid> = ids.iter().map(|id| (*id).into()).collect();
        let placeholders = build_in_clause(ids.len());
        let sql = format!("SELECT * FROM returns WHERE id IN ({placeholders})");

        let params = uuid_params(&raw_ids);
        let params_refs = params_refs(&params);

        let mut stmt = conn.prepare(&sql).map_err(map_db_error)?;
        let returns = stmt
            .query_map(params_refs.as_slice(), Self::row_to_return)
            .map_err(map_db_error)?
            .collect::<rusqlite::Result<Vec<_>>>()
            .map_err(map_db_error)?;

        // Load items for all returns in one batched query
        let ids: Vec<ReturnId> = returns.iter().map(|r| r.id).collect();
        let mut items_by_id = Self::load_return_items_batch(&conn, &ids)?;
        let mut result = vec![];
        for mut ret in returns {
            ret.items = items_by_id.remove(&ret.id.to_string()).unwrap_or_default();
            result.push(ret);
        }

        Ok(result)
    }
}