stateset-http 0.7.20

HTTP service layer (REST + SSE) for the StateSet commerce engine
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
//! Order endpoints.

use axum::{
    Json, Router,
    extract::{Path, Query, State},
    http::HeaderMap,
    routing::{get, patch, post},
};

use crate::dto::{
    CreateOrderItemRequest, CreateOrderRequest, OrderFilterParams, OrderListResponse,
    OrderResponse, decode_cursor, encode_cursor, finalize_page, overfetch_limit,
};
use crate::error::{ErrorBody, HttpError};
use crate::state::{AppState, tenant_id_from_headers};
use stateset_core::{
    Address, CreateOrder, CreateOrderItem, CurrencyCode, CustomerId, FulfillmentStatus,
    OrderFilter, OrderId, OrderStatus, PaymentStatus,
};
use std::str::FromStr;

/// Build the orders sub-router.
pub fn router() -> Router<AppState> {
    Router::new()
        .route("/orders", post(create_order).get(list_orders))
        .route("/orders/{id}", get(get_order))
        .route("/orders/{id}/cancel", patch(cancel_order))
        .route("/orders/{id}/ship", patch(ship_order))
}

/// `POST /api/v1/orders`
#[utoipa::path(
    post,
    path = "/api/v1/orders",
    tag = "orders",
    request_body = CreateOrderRequest,
    responses(
        (status = 201, description = "Order created", body = OrderResponse),
        (status = 400, description = "Invalid request", body = ErrorBody),
    )
)]
#[tracing::instrument(skip(state, headers, req))]
pub(crate) async fn create_order(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(req): Json<CreateOrderRequest>,
) -> Result<(axum::http::StatusCode, Json<OrderResponse>), HttpError> {
    let tenant_id = tenant_id_from_headers(&headers);
    let commerce = state.commerce_for_tenant(tenant_id.as_deref())?;
    let currency = req
        .currency
        .as_deref()
        .map(CurrencyCode::from_str)
        .transpose()
        .map_err(|error| HttpError::BadRequest(format!("Invalid currency: {error}")))?;

    let input = CreateOrder {
        customer_id: req.customer_id,
        items: req.items.into_iter().map(into_core_order_item).collect(),
        currency,
        shipping_address: req.shipping_address.map(Address::from),
        billing_address: req.billing_address.map(Address::from),
        notes: req.notes,
        payment_method: req.payment_method,
        shipping_method: req.shipping_method,
    };
    let order = commerce.orders().create(input)?;
    Ok((axum::http::StatusCode::CREATED, Json(OrderResponse::from(order))))
}

/// `GET /api/v1/orders/:id`
#[utoipa::path(
    get,
    path = "/api/v1/orders/{id}",
    tag = "orders",
    params(("id" = String, Path, description = "Order ID (UUID)")),
    responses(
        (status = 200, description = "Order details", body = OrderResponse),
        (status = 404, description = "Order not found", body = ErrorBody),
    )
)]
#[tracing::instrument(skip(state, headers))]
pub(crate) async fn get_order(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(id): Path<OrderId>,
) -> Result<Json<OrderResponse>, HttpError> {
    let tenant_id = tenant_id_from_headers(&headers);
    let commerce = state.commerce_for_tenant(tenant_id.as_deref())?;
    let order = commerce
        .orders()
        .get(id)?
        .ok_or_else(|| HttpError::NotFound(format!("Order {id} not found")))?;
    Ok(Json(OrderResponse::from(order)))
}

/// `GET /api/v1/orders`
#[utoipa::path(
    get,
    path = "/api/v1/orders",
    tag = "orders",
    params(OrderFilterParams),
    responses(
        (status = 200, description = "List of orders", body = OrderListResponse),
        (status = 400, description = "Invalid filter parameter", body = ErrorBody),
    )
)]
#[tracing::instrument(skip(state, headers, params))]
pub(crate) async fn list_orders(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(params): Query<OrderFilterParams>,
) -> Result<Json<OrderListResponse>, HttpError> {
    let tenant_id = tenant_id_from_headers(&headers);
    let commerce = state.commerce_for_tenant(tenant_id.as_deref())?;

    let limit = params.resolved_limit();
    let offset = params.resolved_offset();

    // Parse filter parameters
    let customer_id = params
        .customer_id
        .map(|s| s.parse::<CustomerId>())
        .transpose()
        .map_err(|e| HttpError::BadRequest(format!("Invalid customer_id: {e}")))?;
    let status = params
        .status
        .as_deref()
        .map(OrderStatus::from_str)
        .transpose()
        .map_err(|e| HttpError::BadRequest(format!("Invalid status: {e}")))?;
    let payment_status = params
        .payment_status
        .as_deref()
        .map(PaymentStatus::from_str)
        .transpose()
        .map_err(|e| HttpError::BadRequest(format!("Invalid payment_status: {e}")))?;
    let fulfillment_status = params
        .fulfillment_status
        .as_deref()
        .map(FulfillmentStatus::from_str)
        .transpose()
        .map_err(|e| HttpError::BadRequest(format!("Invalid fulfillment_status: {e}")))?;
    let from_date = params
        .from_date
        .map(|s| s.parse())
        .transpose()
        .map_err(|e| HttpError::BadRequest(format!("Invalid from_date: {e}")))?;
    let to_date = params
        .to_date
        .map(|s| s.parse())
        .transpose()
        .map_err(|e| HttpError::BadRequest(format!("Invalid to_date: {e}")))?;

    // Decode cursor if provided
    let after_cursor = match &params.after {
        Some(cursor) => Some(
            decode_cursor(cursor).ok_or_else(|| HttpError::BadRequest("Invalid cursor".into()))?,
        ),
        None => None,
    };

    // Count total matching records (without pagination or cursor)
    let count_filter = OrderFilter {
        customer_id,
        status,
        payment_status,
        fulfillment_status,
        from_date,
        to_date,
        limit: None,
        offset: None,
        after_cursor: None,
    };
    let total = commerce.orders().list(count_filter)?.len();

    // Fetch the requested page
    let filter = OrderFilter {
        customer_id,
        status,
        payment_status,
        fulfillment_status,
        from_date,
        to_date,
        limit: Some(overfetch_limit(limit)),
        offset: if after_cursor.is_some() { Some(0) } else { Some(offset) },
        after_cursor,
    };
    let mut orders = commerce.orders().list(filter)?;
    let has_more = finalize_page(&mut orders, limit);
    let next_cursor = if has_more {
        orders.last().map(|o| encode_cursor(&o.order_date.to_rfc3339(), &o.id.to_string()))
    } else {
        None
    };
    Ok(Json(OrderListResponse {
        orders: orders.into_iter().map(OrderResponse::from).collect(),
        total,
        limit,
        offset,
        next_cursor,
        has_more,
    }))
}

/// `PATCH /api/v1/orders/:id/cancel`
#[utoipa::path(
    patch,
    path = "/api/v1/orders/{id}/cancel",
    tag = "orders",
    params(("id" = String, Path, description = "Order ID (UUID)")),
    responses(
        (status = 200, description = "Order cancelled", body = OrderResponse),
        (status = 400, description = "Order cannot be cancelled", body = ErrorBody),
        (status = 404, description = "Order not found", body = ErrorBody),
    )
)]
#[tracing::instrument(skip(state, headers))]
pub(crate) async fn cancel_order(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(id): Path<OrderId>,
) -> Result<Json<OrderResponse>, HttpError> {
    let tenant_id = tenant_id_from_headers(&headers);
    let commerce = state.commerce_for_tenant(tenant_id.as_deref())?;
    let order = commerce.orders().cancel(id)?;
    Ok(Json(OrderResponse::from(order)))
}

/// `PATCH /api/v1/orders/:id/ship`
#[utoipa::path(
    patch,
    path = "/api/v1/orders/{id}/ship",
    tag = "orders",
    params(("id" = String, Path, description = "Order ID (UUID)")),
    responses(
        (status = 200, description = "Order shipped", body = OrderResponse),
        (status = 400, description = "Order cannot be shipped", body = ErrorBody),
        (status = 404, description = "Order not found", body = ErrorBody),
    )
)]
#[tracing::instrument(skip(state, headers))]
pub(crate) async fn ship_order(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(id): Path<OrderId>,
) -> Result<Json<OrderResponse>, HttpError> {
    let tenant_id = tenant_id_from_headers(&headers);
    let commerce = state.commerce_for_tenant(tenant_id.as_deref())?;
    let order = commerce.orders().ship(id, None)?;
    Ok(Json(OrderResponse::from(order)))
}

fn into_core_order_item(item: CreateOrderItemRequest) -> CreateOrderItem {
    CreateOrderItem {
        product_id: item.product_id,
        variant_id: item.variant_id,
        sku: item.sku,
        name: item.name,
        quantity: item.quantity,
        unit_price: item.unit_price,
        discount: item.discount,
        tax_amount: item.tax_amount,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use rust_decimal_macros::dec;
    use stateset_embedded::Commerce;
    use stateset_primitives::ProductId;
    use tower::ServiceExt;

    fn app() -> Router {
        router().with_state(AppState::new(Commerce::new(":memory:").expect("in-memory Commerce")))
    }

    fn app_with_state() -> (Router, AppState) {
        let state = AppState::new(Commerce::new(":memory:").expect("in-memory Commerce"));
        let router = router().with_state(state.clone());
        (router, state)
    }

    #[tokio::test]
    async fn create_order_returns_201() {
        let (app, state) = app_with_state();

        // Create a customer first
        let customer = state
            .commerce()
            .customers()
            .create(stateset_core::CreateCustomer {
                email: "test@example.com".into(),
                first_name: "Test".into(),
                last_name: "User".into(),
                ..Default::default()
            })
            .unwrap();

        // Create a product and variant
        let product = state
            .commerce()
            .products()
            .create(stateset_core::CreateProduct {
                name: "Widget".into(),
                variants: Some(vec![stateset_core::CreateProductVariant {
                    sku: "SKU-001".into(),
                    price: dec!(29.99),
                    ..Default::default()
                }]),
                ..Default::default()
            })
            .unwrap();

        let body = serde_json::json!({
            "customer_id": customer.id,
            "items": [{
                "product_id": product.id,
                "sku": "SKU-001",
                "name": "Widget",
                "quantity": 2,
                "unit_price": "29.99"
            }]
        });

        let resp = app
            .oneshot(
                Request::post("/orders")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);
    }

    #[tokio::test]
    async fn create_order_rejects_invalid_currency() {
        let (app, state) = app_with_state();

        let customer = state
            .commerce()
            .customers()
            .create(stateset_core::CreateCustomer {
                email: "invalid-currency@example.com".into(),
                first_name: "Invalid".into(),
                last_name: "Currency".into(),
                ..Default::default()
            })
            .unwrap();

        let product = state
            .commerce()
            .products()
            .create(stateset_core::CreateProduct {
                name: "Widget".into(),
                variants: Some(vec![stateset_core::CreateProductVariant {
                    sku: "SKU-INVALID-CURRENCY".into(),
                    price: dec!(29.99),
                    ..Default::default()
                }]),
                ..Default::default()
            })
            .unwrap();

        let body = serde_json::json!({
            "customer_id": customer.id,
            "currency": "USDX",
            "items": [{
                "product_id": product.id,
                "sku": "SKU-INVALID-CURRENCY",
                "name": "Widget",
                "quantity": 1,
                "unit_price": "29.99"
            }]
        });

        let resp = app
            .oneshot(
                Request::post("/orders")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn list_orders_reports_total_before_pagination() {
        let (app, state) = app_with_state();

        let customer = state
            .commerce()
            .customers()
            .create(stateset_core::CreateCustomer {
                email: "paging-orders@example.com".into(),
                first_name: "Paging".into(),
                last_name: "Orders".into(),
                ..Default::default()
            })
            .unwrap();

        let product = state
            .commerce()
            .products()
            .create(stateset_core::CreateProduct {
                name: "Paging Widget".into(),
                variants: Some(vec![stateset_core::CreateProductVariant {
                    sku: "PAGE-ORD-001".into(),
                    price: dec!(9.99),
                    ..Default::default()
                }]),
                ..Default::default()
            })
            .unwrap();

        for _ in 0..2 {
            state
                .commerce()
                .orders()
                .create(stateset_core::CreateOrder {
                    customer_id: customer.id,
                    items: vec![stateset_core::CreateOrderItem {
                        product_id: product.id,
                        variant_id: None,
                        sku: "PAGE-ORD-001".into(),
                        name: "Paging Widget".into(),
                        quantity: 1,
                        unit_price: dec!(9.99),
                        discount: None,
                        tax_amount: None,
                    }],
                    ..Default::default()
                })
                .unwrap();
        }

        let resp = app
            .oneshot(Request::get("/orders?limit=1&offset=0").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["total"], 2);
        assert_eq!(json["orders"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn get_order_not_found() {
        let id = OrderId::new();
        let resp = app()
            .oneshot(Request::get(format!("/orders/{id}")).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn list_orders_empty() {
        let resp =
            app().oneshot(Request::get("/orders").body(Body::empty()).unwrap()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["total"], 0);
        assert!(json["orders"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn list_orders_with_pagination() {
        let resp = app()
            .oneshot(Request::get("/orders?limit=10&offset=5").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["limit"], 10);
        assert_eq!(json["offset"], 5);
    }

    #[tokio::test]
    async fn cancel_nonexistent_order_fails() {
        let id = OrderId::new();
        let resp = app()
            .oneshot(
                Request::builder()
                    .method("PATCH")
                    .uri(format!("/orders/{id}/cancel"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // Should be 404 or 400 depending on error mapping
        assert!(resp.status().is_client_error());
    }

    #[test]
    fn into_core_order_item_converts() {
        let req = CreateOrderItemRequest {
            product_id: ProductId::new(),
            variant_id: None,
            sku: "SKU".into(),
            name: "Name".into(),
            quantity: 1,
            unit_price: dec!(10),
            discount: Some(dec!(1)),
            tax_amount: None,
        };
        let core = into_core_order_item(req);
        assert_eq!(core.sku, "SKU");
        assert_eq!(core.discount, Some(dec!(1)));
    }

    #[tokio::test]
    async fn list_orders_filter_by_customer_id() {
        let (app, state) = app_with_state();

        let cust_a = state
            .commerce()
            .customers()
            .create(stateset_core::CreateCustomer {
                email: "a@example.com".into(),
                first_name: "A".into(),
                last_name: "A".into(),
                ..Default::default()
            })
            .unwrap();
        let cust_b = state
            .commerce()
            .customers()
            .create(stateset_core::CreateCustomer {
                email: "b@example.com".into(),
                first_name: "B".into(),
                last_name: "B".into(),
                ..Default::default()
            })
            .unwrap();

        let product = state
            .commerce()
            .products()
            .create(stateset_core::CreateProduct {
                name: "Filter Widget".into(),
                variants: Some(vec![stateset_core::CreateProductVariant {
                    sku: "FILT-001".into(),
                    price: dec!(5.00),
                    ..Default::default()
                }]),
                ..Default::default()
            })
            .unwrap();

        let make_item = || stateset_core::CreateOrderItem {
            product_id: product.id,
            variant_id: None,
            sku: "FILT-001".into(),
            name: "Filter Widget".into(),
            quantity: 1,
            unit_price: dec!(5.00),
            discount: None,
            tax_amount: None,
        };

        // 2 orders for cust_a, 1 for cust_b
        for _ in 0..2 {
            state
                .commerce()
                .orders()
                .create(stateset_core::CreateOrder {
                    customer_id: cust_a.id,
                    items: vec![make_item()],
                    ..Default::default()
                })
                .unwrap();
        }
        state
            .commerce()
            .orders()
            .create(stateset_core::CreateOrder {
                customer_id: cust_b.id,
                items: vec![make_item()],
                ..Default::default()
            })
            .unwrap();

        let resp = app
            .oneshot(
                Request::get(format!("/orders?customer_id={}", cust_a.id))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["total"], 2);
        assert_eq!(json["orders"].as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn list_orders_invalid_status_returns_400() {
        let resp = app()
            .oneshot(Request::get("/orders?status=bogus").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn list_orders_invalid_customer_id_returns_400() {
        let resp = app()
            .oneshot(Request::get("/orders?customer_id=not-a-uuid").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn list_orders_invalid_date_returns_400() {
        let resp = app()
            .oneshot(Request::get("/orders?from_date=not-a-date").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn list_orders_has_more_and_next_cursor() {
        let (_, state) = app_with_state();

        let customer = state
            .commerce()
            .customers()
            .create(stateset_core::CreateCustomer {
                email: "cursor@example.com".into(),
                first_name: "Cursor".into(),
                last_name: "Test".into(),
                ..Default::default()
            })
            .unwrap();

        let product = state
            .commerce()
            .products()
            .create(stateset_core::CreateProduct {
                name: "Cursor Widget".into(),
                variants: Some(vec![stateset_core::CreateProductVariant {
                    sku: "CUR-001".into(),
                    price: dec!(5.00),
                    ..Default::default()
                }]),
                ..Default::default()
            })
            .unwrap();

        // Create 3 orders
        for _ in 0..3 {
            state
                .commerce()
                .orders()
                .create(stateset_core::CreateOrder {
                    customer_id: customer.id,
                    items: vec![stateset_core::CreateOrderItem {
                        product_id: product.id,
                        variant_id: None,
                        sku: "CUR-001".into(),
                        name: "Cursor Widget".into(),
                        quantity: 1,
                        unit_price: dec!(5.00),
                        discount: None,
                        tax_amount: None,
                    }],
                    ..Default::default()
                })
                .unwrap();
        }

        // Request page of size 2 — should have has_more=true and next_cursor
        let app = router().with_state(state.clone());
        let resp = app
            .oneshot(Request::get("/orders?limit=2").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["total"], 3);
        assert_eq!(json["orders"].as_array().unwrap().len(), 2);
        assert_eq!(json["has_more"], true);
        let cursor = json["next_cursor"].as_str().expect("next_cursor should be present");

        // Use cursor to fetch the next page
        let app2 = router().with_state(state);
        let resp2 = app2
            .oneshot(
                Request::get(format!("/orders?limit=2&after={cursor}"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp2.status(), StatusCode::OK);
        let body2 = axum::body::to_bytes(resp2.into_body(), usize::MAX).await.unwrap();
        let json2: serde_json::Value = serde_json::from_slice(&body2).unwrap();

        assert_eq!(json2["orders"].as_array().unwrap().len(), 1);
        assert_eq!(json2["has_more"], false);
        assert!(json2.get("next_cursor").is_none() || json2["next_cursor"].is_null());
    }

    #[tokio::test]
    async fn list_orders_exact_boundary_has_more_false() {
        let (_, state) = app_with_state();

        let customer = state
            .commerce()
            .customers()
            .create(stateset_core::CreateCustomer {
                email: "cursor-boundary@example.com".into(),
                first_name: "Cursor".into(),
                last_name: "Boundary".into(),
                ..Default::default()
            })
            .unwrap();

        let product = state
            .commerce()
            .products()
            .create(stateset_core::CreateProduct {
                name: "Boundary Widget".into(),
                variants: Some(vec![stateset_core::CreateProductVariant {
                    sku: "CUR-BOUNDARY-001".into(),
                    price: dec!(5.00),
                    ..Default::default()
                }]),
                ..Default::default()
            })
            .unwrap();

        for _ in 0..2 {
            state
                .commerce()
                .orders()
                .create(stateset_core::CreateOrder {
                    customer_id: customer.id,
                    items: vec![stateset_core::CreateOrderItem {
                        product_id: product.id,
                        variant_id: None,
                        sku: "CUR-BOUNDARY-001".into(),
                        name: "Boundary Widget".into(),
                        quantity: 1,
                        unit_price: dec!(5.00),
                        discount: None,
                        tax_amount: None,
                    }],
                    ..Default::default()
                })
                .unwrap();
        }

        let app = router().with_state(state);
        let resp = app
            .oneshot(Request::get("/orders?limit=2").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["total"], 2);
        assert_eq!(json["orders"].as_array().unwrap().len(), 2);
        assert_eq!(json["has_more"], false);
        assert!(json.get("next_cursor").is_none() || json["next_cursor"].is_null());
    }

    #[tokio::test]
    async fn list_orders_invalid_cursor_returns_400() {
        let resp = app()
            .oneshot(Request::get("/orders?after=!!!invalid!!!").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn list_orders_empty_has_more_false() {
        let resp =
            app().oneshot(Request::get("/orders").body(Body::empty()).unwrap()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["has_more"], false);
        assert!(json.get("next_cursor").is_none() || json["next_cursor"].is_null());
    }
}