File size: 29,834 Bytes
c33971d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use crate::domain::error::{AppError, AppResult};
use crate::domain::models::OrderRecord;
use crate::infrastructure::db::DbPool;
use crate::infrastructure::repositories::{MerchantRepository, OrderRepository, ProductRepository};
use crate::infrastructure::storage::assets::AssetProvider;
use crate::interfaces::http::api::RealtimeEvent;
use std::sync::Arc;
use tokio::sync::broadcast::Sender;
use uuid::Uuid;

#[allow(clippy::too_many_arguments)]
pub async fn execute_checkout_helper(
    product_repo: &Arc<dyn ProductRepository>,
    merchant_repo: &Arc<dyn MerchantRepository>,
    order_repo: &Arc<dyn OrderRepository>,
    pool: &DbPool,
    tx_sender: &Sender<RealtimeEvent>,
    link_id: &str,
    buyer_phone: &str,
    buyer_name: &str,
    buyer_email: &str,
    shipping_pincode: &str,
    delivery_address: &str,
    coupon_code: Option<String>,
    request_id: Option<String>,
    client_ip: &str,
    lat: Option<f64>,
    lng: Option<f64>,
    device_fingerprint: Option<String>,
) -> AppResult<OrderRecord> {
    let product = product_repo.find_by_id(link_id).await?;
    let mut product =
        product.ok_or_else(|| AppError::NotFound("Product link not found".to_string()))?;

    let _ = product_repo.increment_views(link_id).await;
    product.image_data = crate::core::utils::hydrate_file_to_base64(product.image_data).await;

    let merchant = merchant_repo
        .find_by_id(&product.merchant_id)
        .await?
        .ok_or_else(|| AppError::NotFound("Merchant not found".to_string()))?;

    if merchant.is_frozen {
        return Err(AppError::Forbidden(
            "Merchant account is frozen due to unpaid outstanding invoices.".to_string(),
        ));
    }

    // 1. Secure Logistics Circuit Breaker
    // Check if the pincode has high smart volatility (recent violations)
    let volatility_count = sqlx::query_scalar::<_, i64>(
        "SELECT COUNT(*) FROM risk_audit_logs WHERE details LIKE $1 AND created_at > NOW() - INTERVAL '1 hour'"
    )
    .bind(format!("%{}%", shipping_pincode))
    .fetch_one(order_repo.find_pool())
    .await
    .unwrap_or(0);

    if volatility_count > 5 {
        return Err(AppError::Forbidden(format!(
            "Logistics Circuit Breaker Active for zone {}. High volatility detected in recent smart audit cycles.",
            shipping_pincode
        )));
    }

    // 2. Institutional Velocity Guard (Anti-Abuse)
    let intelligence =
        crate::application::services::intelligence::IntelligenceService::new(pool.clone());
    let velocity_risk = intelligence
        .evaluate_velocity_risk(
            device_fingerprint.as_deref(),
            Some(client_ip),
            &product.merchant_id,
        )
        .await?;

    if velocity_risk >= 90.0 {
        // Log Critical Security Event
        let _ = sqlx::query(
            "INSERT INTO risk_audit_logs (merchant_id, event_type, risk_level, details, device_fingerprint) VALUES ($1, $2, $3, $4, $5)"
        )
        .bind(&product.merchant_id)
        .bind("VELOCITY_BLOCK")
        .bind("CRITICAL")
        .bind(format!("Transaction blocked due to high velocity risk ({}). Fingerprint: {:?}, IP: {}", velocity_risk, device_fingerprint, client_ip))
        .bind(device_fingerprint.as_deref())
        .execute(pool)
        .await;

        return Err(AppError::Forbidden(
            "Security Protocol Active: High-frequency transaction activity detected from this device/network. Access restricted for protocol safety.".to_string()
        ));
    }

    let distance_km =
        crate::domain::distance::estimate_distance_km(&merchant.base_pincode, shipping_pincode);

    let pricing_features = crate::application::services::pricing::PricingFeatures {
        distance_km,
        user_rate_per_km: merchant.delivery_rate_per_km,
        product_weight: product.expected_weight,
        base_charge: merchant.delivery_base_fee,
        config: serde_json::from_value(merchant.logistics_config.clone()).unwrap_or_default(),
    };
    let delivery_fee = crate::application::services::pricing::PricingEngine::estimate_delivery_fee(
        pricing_features,
    );

    // 3. Precision Geofence Check
    let mut geofence_verified = None;
    if let (Some(l_lat), Some(l_lng)) = (lat, lng) {
        let intelligence =
            crate::application::services::intelligence::IntelligenceService::new(pool.clone());
        if !intelligence
            .verify_geofence_with_precision(shipping_pincode, l_lat, l_lng)
            .await?
        {
            return Err(AppError::Forbidden(format!(
                "Geofence Verification Failed: Your current GPS coordinates do not match the shipping pincode {}. Forensic integrity active.",
                shipping_pincode
            )));
        }
        geofence_verified = Some(true);
    }

    let order_count = order_repo
        .count_by_buyer(&product.merchant_id, buyer_phone)
        .await?;

    let transaction_id = Uuid::new_v4().to_string();

    // 2. Merchant Transaction Limits
    if merchant.plan == "FREE" && product.price_inr > 10000.0 {
        return Err(AppError::Forbidden(
            "Transaction value exceeds the ₹10,000 limit for merchants on the FREE plan. Upgrade to PRO to accept higher-value payments without limitations.".to_string()
        ));
    }

    if product.price_inr > merchant.max_order_value_inr {
        return Err(AppError::Forbidden(format!(
            "Transaction value ₹{} exceeds the current limit for this merchant (₹{}). Increase merchant verification level to lift this restriction.",
            product.price_inr, merchant.max_order_value_inr
        )));
    }

    // Start Transaction for Atomicity
    let mut tx = pool.begin().await.map_err(AppError::Database)?;

    // 3. Inventory Preliminary Check
    if !product.is_unlimited && product.inventory_count <= 0 {
        return Err(AppError::BadRequest(
            "Product is currently out of stock.".to_string(),
        ));
    }

    let current_price =
        if let (Some(sale_price), Some(ends_at)) = (product.sale_price_inr, product.sale_ends_at) {
            if ends_at > chrono::Utc::now().naive_utc() {
                sale_price
            } else {
                product.price_inr
            }
        } else {
            product.price_inr
        };

    let platform_fee = crate::application::services::pricing::PricingEngine::calculate_platform_fee(
        current_price,
        merchant.trust_score,
    );

    // Calculate preliminary risk score
    let mut calculated_risk = 0.0;
    calculated_risk += (volatility_count as f64 * 5.0).min(30.0);
    calculated_risk += velocity_risk * 0.4; // Incorporate velocity guard signal
    if geofence_verified == Some(true) {
        calculated_risk *= 0.8; // Lower risk if GPS verified
    }

    let mut order = OrderRecord {
        transaction_id: transaction_id.clone(),
        merchant_id: product.merchant_id.clone(),
        link_id: link_id.to_string(),
        buyer_phone: buyer_phone.to_string(),
        buyer_phone_hash: None, // populated by encrypt_pii() at persist time
        buyer_name: buyer_name.to_string(),
        buyer_email: buyer_email.to_string(),
        shipping_pincode: Some(shipping_pincode.to_string()),
        delivery_address: Some(delivery_address.to_string()),
        price_inr: current_price,
        status: crate::domain::constants::ORDER_STATUS_PENDING_PAYMENT.to_string(),
        vpa: None,
        payu_id: String::new(),
        outbound_weight: product.expected_weight,
        return_weight: 0.0,
        proof_data: None,
        settled_at: None,
        shipped_at: None,
        delivered_at: None,
        shipping_method: None,
        estimated_delivery_at: None,
        is_payment: false,
        platform_fee_paid: false,
        platform_fee,
        delivery_fee,
        distance_km,
        risk_score: calculated_risk,
        risk_flags: None,
        cgst: 0.0,
        sgst: 0.0,
        igst: 0.0,
        utr_number: None,
        platform_fee_utr: None,
        delivery_gps_lat: None,
        delivery_gps_lng: None,
        is_geofence_verified: geofence_verified,
        pincode_volatility_at_checkout: 0.0,
        discount_amount: 0.0,
        coupon_code: None,
        checkout_gps_lat: lat,
        checkout_gps_lng: lng,
        device_fingerprint: device_fingerprint.clone(),
        paid_at: None,
        proof_received_at: None,
        created_at: None,
        brand_name: None,
    };

    if let Some(ref code) = coupon_code {
        let coupon = sqlx::query_as::<_, crate::domain::models::Coupon>(
            "SELECT * FROM coupons WHERE merchant_id = $1 AND code = $2 AND is_active = TRUE",
        )
        .bind(&product.merchant_id)
        .bind(code.to_uppercase())
        .fetch_optional(&mut *tx)
        .await?;

        if let Some(c) = coupon {
            if c.is_valid(order.price_inr) {
                let discount = c.calculate_discount(order.price_inr);
                order.discount_amount = discount;
                order.price_inr -= discount;
                order.coupon_code = Some(code.clone());
            }
        }
    }

    let gst_breakdown = crate::application::services::india_tax::IndiaTaxService::calculate_gst(
        order.price_inr,
        merchant.state_code.unwrap_or(29),
        order.shipping_pincode.as_deref().unwrap_or_default(),
        0.18, // 18% standard rate
    );
    order.cgst = gst_breakdown.cgst;
    order.sgst = gst_breakdown.sgst;
    order.igst = gst_breakdown.igst;

    let volatility =
        crate::application::services::intelligence::IntelligenceService::new(pool.clone())
            .get_pincode_volatility(order.shipping_pincode.as_deref().unwrap_or_default())
            .await
            .unwrap_or(0.0);
    order.pincode_volatility_at_checkout = volatility;

    if volatility > 0.5 {
        let _ = tx_sender.send(
            crate::interfaces::http::api::RealtimeEvent::NetworkVolatilityAlert {
                pincode: order.shipping_pincode.clone().unwrap_or_default(),
                volatility_score: volatility,
                message: format!(
                    "High logistics volatility detected for pincode {}.",
                    order.shipping_pincode.clone().unwrap_or_default()
                ),
            },
        );
    }

    let (risk_score, risk_flags) =
        crate::application::services::risk::RiskEngine::calculate_risk_score(
            &order,
            order_count,
            volatility,
        );
    order.risk_score = risk_score;
    order.risk_flags = Some(risk_flags);

    if order.risk_score >= 80.0 {
        // Log Critical/High Security Event outside the transaction so it's persisted even when rolled back
        if let Ok(mut conn) = pool.acquire().await {
            crate::domain::audit::log_risk_event(
                &mut conn,
                Some(&transaction_id),
                &product.merchant_id,
                "HIGH_RISK_BLOCK",
                "CRITICAL",
                Some(&format!(
                    "Transaction blocked due to high risk score ({:.1}) during checkout for link {}. Flags: {:?}",
                    order.risk_score, link_id, order.risk_flags
                )),
                Some(order.risk_score),
                request_id.as_deref(),
                device_fingerprint.as_deref(),
                Some(tx_sender),
            )
            .await;
        }

        if order.risk_score > 90.0 {
            crate::interfaces::http::middleware::block_ip_persistently(
                pool,
                client_ip,
                &format!("Automated Defense: High Risk Score ({:.1}) detected during checkout for link {}", order.risk_score, link_id),
                Some(tx_sender)
            ).await;
        }

        return Err(AppError::Forbidden(format!(
            "Security restriction: High risk profile detected (Score: {:.1}). This transaction has been blocked to prevent potential fraud.",
            order.risk_score
        )));
    } else if order.risk_score > 60.0 {
        crate::domain::audit::log_risk_event(
            &mut tx,
            Some(&transaction_id),
            &product.merchant_id,
            "HIGH_RISK_ORDER",
            "HIGH",
            Some(&format!(
                "Order {} flagged with risk score {}",
                transaction_id, order.risk_score
            )),
            Some(order.risk_score),
            request_id.as_deref(),
            device_fingerprint.as_deref(),
            Some(tx_sender),
        )
        .await;
    }

    // Persist Order using transaction
    order.created_at = Some(chrono::Utc::now().naive_utc());
    crate::domain::models::OrderRecord::create_with_tx(&mut tx, &order).await?;

    tx.commit().await.map_err(AppError::Database)?;

    Ok(order)
}

#[allow(clippy::too_many_arguments)]
pub async fn execute_submit_delivery_proof_helper(
    order_repo: &Arc<dyn OrderRepository>,
    assets: &Arc<dyn AssetProvider>,
    tx_sender: &Sender<RealtimeEvent>,
    transaction_id: &str,
    proof_data: &str,
    proof_token: &str,
    lat: Option<f64>,
    lng: Option<f64>,
) -> AppResult<()> {
    let transaction_id = crate::domain::validation::sanitize_filename(transaction_id);

    if crate::core::session::verify_proof_token(proof_token, &transaction_id).is_err() {
        return Err(AppError::Forbidden(
            "Invalid proof authorization token".to_string(),
        ));
    }

    let order = order_repo.find_by_id(&transaction_id).await?;
    let order = order.ok_or_else(|| AppError::NotFound("Order not found".to_string()))?;

    if order.status != crate::domain::constants::ORDER_STATUS_PAID_PENDING_DELIVERY {
        return Err(AppError::BadRequest(
            "Order is not in a state to accept delivery proof".to_string(),
        ));
    }

    let mut tx = order_repo
        .find_pool()
        .begin()
        .await
        .map_err(AppError::Database)?;

    let is_video = proof_data.contains("video") && proof_data.contains("mp4");
    let is_png = proof_data.contains("image/png");
    let file_extension = if is_video {
        "mp4"
    } else if is_png {
        "png"
    } else {
        "jpg"
    };
    let filename = format!("proof_{}.{}", Uuid::new_v4(), file_extension);

    let bytes = crate::domain::validation::validate_base64_payload(proof_data, 10 * 1024 * 1024)
        .map_err(|e| AppError::BadRequest(e.message))?;

    // Institutional Enforcement: Require Video for High-Value Orders (> ₹5,000)
    if order.price_inr > 5000.0 && !is_video {
        return Err(AppError::BadRequest(
            "High-value order detected. Smart video proof is mandatory for this transaction."
                .to_string(),
        ));
    }

    if !is_video {
        let allowed_headers: [Vec<u8>; 2] = [
            vec![0xFF, 0xD8, 0xFF],
            vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
        ];
        if !allowed_headers
            .iter()
            .any(|header| bytes.starts_with(header))
        {
            return Err(AppError::BadRequest("Invalid image format".to_string()));
        }
    }

    let merchant_plan: String =
        sqlx::query_scalar("SELECT plan FROM merchants WHERE merchant_id = $1")
            .bind(&order.merchant_id)
            .fetch_one(&mut *tx)
            .await
            .map_err(AppError::Database)?;

    let lat_val = lat.unwrap_or(0.0);
    let lng_val = lng.unwrap_or(0.0);
    let mut zk_proof = crate::core::crypto::CryptoService::generate_zk_telemetry_proof(
        &transaction_id,
        &bytes,
        lat_val,
        lng_val,
    );

    if merchant_plan == "PRO" {
        let asset_path = assets
            .store_asset(&filename, &bytes)
            .await
            .map_err(AppError::Internal)?;

        if let Some(obj) = zk_proof.as_object_mut() {
            obj.insert("is_zero_storage".to_string(), serde_json::json!(false));
            obj.insert("asset_path".to_string(), serde_json::json!(asset_path));
        }
    }

    let mut is_geofence_verified = None;
    if let (Some(l_lat), Some(l_lng), Some(pincode)) = (lat, lng, &order.shipping_pincode) {
        let (p_lat, p_lng) = crate::domain::geofence::GeofenceService::get_coordinates(pincode)
            .unwrap_or((12.9716, 77.5946)); // Default to Bangalore Central

        let distance = crate::domain::geofence::GeofenceService::calculate_distance_km(
            l_lat, l_lng, p_lat, p_lng,
        );
        is_geofence_verified = Some(distance < 5.0); // 5km tolerance

        if !is_geofence_verified.unwrap_or(false) {
            crate::domain::audit::log_risk_event(
                &mut tx,
                Some(&transaction_id),
                &order.merchant_id,
                "GEOFENCE_VIOLATION",
                "MEDIUM",
                Some(&format!(
                    "Delivery proof submitted from {} km away from shipping pincode {}.",
                    distance.round(),
                    pincode
                )),
                Some(distance),
                None,
                order.device_fingerprint.as_deref(),
                Some(tx_sender),
            )
            .await;

            // Trust Score Penalty for logistics deviations
            let _ = sqlx::query("UPDATE merchants SET trust_score = GREATEST(0.0, trust_score - 2.0) WHERE merchant_id = $1")
                .bind(&order.merchant_id)
                .execute(&mut *tx)
                .await;
        }
    }

    sqlx::query(
        "UPDATE orders SET proof_data = proof_data || $1::jsonb, status = $2, delivered_at = CURRENT_TIMESTAMP, delivery_gps_lat = $3, delivery_gps_lng = $4, is_geofence_verified = $5 WHERE transaction_id = $6 AND status = $7",
    )
    .bind(serde_json::json!([zk_proof]))
    .bind(crate::domain::constants::ORDER_STATUS_DELIVERED_PENDING_APPROVAL)
    .bind(lat)
    .bind(lng)
    .bind(is_geofence_verified)
    .bind(&transaction_id)
    .bind(crate::domain::constants::ORDER_STATUS_PAID_PENDING_DELIVERY)
    .execute(&mut *tx)
    .await
    .map_err(AppError::Database)?;

    tx.commit().await.map_err(AppError::Database)?;

    let _ = tx_sender.send(
        crate::interfaces::http::api::RealtimeEvent::OrderStatusChanged {
            transaction_id: transaction_id.to_string(),
            merchant_id: order.merchant_id,
            new_status: crate::domain::constants::ORDER_STATUS_DELIVERED_PENDING_APPROVAL
                .to_string(),
        },
    );

    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn execute_cart_checkout_helper(
    product_repo: &Arc<dyn crate::infrastructure::repositories::ProductRepository>,
    merchant_repo: &Arc<dyn crate::infrastructure::repositories::MerchantRepository>,
    _order_repo: &Arc<dyn crate::infrastructure::repositories::OrderRepository>,
    pool: &crate::infrastructure::db::DbPool,
    tx_sender: &tokio::sync::broadcast::Sender<crate::interfaces::http::api::RealtimeEvent>,
    items: Vec<(String, u32)>,
    buyer_phone: &str,
    buyer_name: &str,
    buyer_email: &str,
    shipping_pincode: &str,
    delivery_address: &str,
    coupon_code: Option<String>,
    _request_id: Option<String>,
    client_ip: &str,
    lat: Option<f64>,
    lng: Option<f64>,
    device_fingerprint: Option<String>,
) -> AppResult<crate::domain::models::OrderRecord> {
    let transaction_id = format!(
        "TX_{}",
        uuid::Uuid::new_v4().to_string()[..8].to_uppercase()
    );

    let mut total_price = 0.0;
    let mut total_weight = 0.0;
    let mut first_merchant_id = String::new();
    let mut product_details = Vec::new();

    for (link_id, qty) in &items {
        let product = product_repo
            .find_by_id(link_id)
            .await?
            .ok_or_else(|| AppError::NotFound(format!("Product {} not found", link_id)))?;

        if first_merchant_id.is_empty() {
            first_merchant_id = product.merchant_id.clone();
        } else if first_merchant_id != product.merchant_id {
            return Err(AppError::BadRequest(
                "Cross-merchant checkout not allowed in single cart".into(),
            ));
        }

        let current_price = if let (Some(sale_price), Some(ends_at)) =
            (product.sale_price_inr, product.sale_ends_at)
        {
            if ends_at > chrono::Utc::now().naive_utc() {
                sale_price
            } else {
                product.price_inr
            }
        } else {
            product.price_inr
        };

        total_price += current_price * (*qty as f64);
        total_weight += product.expected_weight * (*qty as f64);

        // Inventory Enforcement for Cart (Preliminary Check)
        if !product.is_unlimited && product.inventory_count < *qty as i32 {
            return Err(AppError::BadRequest(format!(
                "Product '{}' is low on stock ({} available).",
                product.product_name, product.inventory_count
            )));
        }

        product_details.push((product, *qty));
    }

    if first_merchant_id.is_empty() {
        return Err(AppError::BadRequest("Cart is empty".into()));
    }

    let merchant = merchant_repo
        .find_by_id(&first_merchant_id)
        .await?
        .ok_or_else(|| AppError::NotFound("Merchant not found".into()))?;

    if merchant.is_frozen {
        return Err(AppError::Forbidden(
            "Merchant account is frozen due to unpaid outstanding invoices.".to_string(),
        ));
    }

    // 2. Institutional Velocity Guard (Anti-Abuse)
    let intelligence =
        crate::application::services::intelligence::IntelligenceService::new(pool.clone());
    let velocity_risk = intelligence
        .evaluate_velocity_risk(
            device_fingerprint.as_deref(),
            Some(client_ip),
            &first_merchant_id,
        )
        .await?;

    if velocity_risk >= 90.0 {
        return Err(AppError::Forbidden(
            "Security Protocol Active: High-frequency transaction activity detected from this device/network. Access restricted for protocol safety.".to_string()
        ));
    }

    let distance_km =
        crate::domain::distance::estimate_distance_km(&merchant.base_pincode, shipping_pincode);

    let pricing_features = crate::application::services::pricing::PricingFeatures {
        distance_km,
        user_rate_per_km: merchant.delivery_rate_per_km,
        product_weight: total_weight,
        base_charge: merchant.delivery_base_fee,
        config: serde_json::from_value(merchant.logistics_config.clone()).unwrap_or_default(),
    };

    let delivery_fee = crate::application::services::pricing::PricingEngine::estimate_delivery_fee(
        pricing_features,
    );

    // Precision Geofence Check
    let mut geofence_verified = None;
    if let (Some(l_lat), Some(l_lng)) = (lat, lng) {
        let intelligence =
            crate::application::services::intelligence::IntelligenceService::new(pool.clone());
        if !intelligence
            .verify_geofence_with_precision(shipping_pincode, l_lat, l_lng)
            .await?
        {
            return Err(AppError::Forbidden(format!(
                "Geofence Verification Failed: Your current GPS coordinates do not match the shipping pincode {}. Forensic integrity active.",
                shipping_pincode
            )));
        }
        geofence_verified = Some(true);
    }
    let platform_fee = crate::application::services::pricing::PricingEngine::calculate_platform_fee(
        total_price,
        merchant.trust_score,
    );

    let gst_breakdown = crate::application::services::india_tax::IndiaTaxService::calculate_gst(
        total_price,
        merchant.state_code.unwrap_or(29),
        shipping_pincode,
        0.18,
    );

    let volatility =
        crate::application::services::intelligence::IntelligenceService::new(pool.clone())
            .get_pincode_volatility(shipping_pincode)
            .await
            .unwrap_or(0.0);

    // Calculate preliminary risk score
    let mut calculated_risk = 0.0;
    calculated_risk += (volatility * 50.0).min(30.0);
    calculated_risk += velocity_risk * 0.4;
    if geofence_verified == Some(true) {
        calculated_risk *= 0.8;
    }

    let mut order = crate::domain::models::OrderRecord {
        transaction_id: transaction_id.clone(),
        merchant_id: first_merchant_id.clone(),
        link_id: "CART_TRANSACTION".into(),
        buyer_phone: buyer_phone.to_string(),
        buyer_phone_hash: None, // populated by encrypt_pii() at persist time
        buyer_name: buyer_name.to_string(),
        buyer_email: buyer_email.to_string(),
        shipping_pincode: Some(shipping_pincode.to_string()),
        delivery_address: Some(delivery_address.to_string()),
        price_inr: total_price,
        status: crate::domain::constants::ORDER_STATUS_PENDING_PAYMENT.to_string(),
        vpa: Some(String::new()),
        outbound_weight: total_weight,
        return_weight: 0.0,
        proof_data: Some(serde_json::json!([])),
        settled_at: None,
        shipped_at: None,
        delivered_at: None,
        shipping_method: None,
        estimated_delivery_at: None,
        payu_id: String::new(),
        is_payment: false,
        platform_fee_paid: false,
        platform_fee,
        delivery_fee,
        distance_km,
        risk_score: calculated_risk,
        risk_flags: None,
        cgst: gst_breakdown.cgst,
        sgst: gst_breakdown.sgst,
        igst: gst_breakdown.igst,
        utr_number: None,
        platform_fee_utr: None,
        delivery_gps_lat: None,
        delivery_gps_lng: None,
        is_geofence_verified: geofence_verified,
        pincode_volatility_at_checkout: volatility,
        discount_amount: 0.0,
        coupon_code: None,
        checkout_gps_lat: lat,
        checkout_gps_lng: lng,
        device_fingerprint: device_fingerprint.clone(),
        paid_at: None,
        proof_received_at: None,
        created_at: None,
        brand_name: None,
    };

    let mut tx = pool.begin().await.map_err(AppError::Database)?;

    // Cart inventory checked previously. Will be decremented upon payment success.

    if let Some(ref code) = coupon_code {
        let coupon = sqlx::query_as::<_, crate::domain::models::Coupon>(
            "SELECT * FROM coupons WHERE merchant_id = $1 AND code = $2 AND is_active = TRUE",
        )
        .bind(&first_merchant_id)
        .bind(code.to_uppercase())
        .fetch_optional(&mut *tx)
        .await?;

        if let Some(c) = coupon {
            if c.is_valid(order.price_inr) {
                let discount = c.calculate_discount(order.price_inr);
                order.discount_amount = discount;
                order.price_inr -= discount;
                order.coupon_code = Some(code.clone());
            }
        }
    }

    let (risk_score, risk_flags) =
        crate::application::services::risk::RiskEngine::calculate_risk_score(&order, 0, volatility);
    order.risk_score = risk_score;
    order.risk_flags = Some(risk_flags);

    if order.risk_score >= 80.0 {
        // Log Critical/High Security Event outside the transaction so it's persisted even when rolled back
        if let Ok(mut conn) = pool.acquire().await {
            crate::domain::audit::log_risk_event(
                &mut conn,
                Some(&transaction_id),
                &first_merchant_id,
                "HIGH_RISK_BLOCK",
                "CRITICAL",
                Some(&format!(
                    "Cart transaction blocked due to high risk score ({:.1}) during checkout. Flags: {:?}",
                    order.risk_score, order.risk_flags
                )),
                Some(order.risk_score),
                None,
                device_fingerprint.as_deref(),
                Some(tx_sender),
            )
            .await;
        }

        if order.risk_score > 90.0 {
            crate::interfaces::http::middleware::block_ip_persistently(
                pool,
                client_ip,
                &format!(
                    "Automated Defense: High Risk Score ({:.1}) detected during cart checkout",
                    order.risk_score
                ),
                Some(tx_sender),
            )
            .await;
        }

        return Err(AppError::Forbidden(format!(
            "Security restriction: High risk profile detected (Score: {:.1}). This transaction has been blocked to prevent potential fraud.",
            order.risk_score
        )));
    } else if order.risk_score > 60.0 {
        crate::domain::audit::log_risk_event(
            &mut tx,
            Some(&transaction_id),
            &first_merchant_id,
            "HIGH_RISK_ORDER",
            "HIGH",
            Some(&format!(
                "Cart order {} flagged with risk score {}",
                transaction_id, order.risk_score
            )),
            Some(order.risk_score),
            None,
            device_fingerprint.as_deref(),
            Some(tx_sender),
        )
        .await;
    }

    // Persist Order
    order.created_at = Some(chrono::Utc::now().naive_utc());
    crate::domain::models::OrderRecord::create_with_tx(&mut tx, &order).await?;

    // Persist Order Items
    for (p, qty) in product_details {
        sqlx::query(
            "INSERT INTO order_items (transaction_id, product_id, product_name, quantity, price_at_checkout, weight_at_checkout) VALUES ($1, $2, $3, $4, $5, $6)"
        )
        .bind(&transaction_id)
        .bind(&p.link_id)
        .bind(&p.product_name)
        .bind(qty as i32)
        .bind(p.price_inr)
        .bind(p.expected_weight)
        .execute(&mut *tx)
        .await
        .map_err(AppError::Database)?;
    }
    tx.commit().await.map_err(AppError::Database)?;

    Ok(order)
}