bctx-cloud-core 0.1.30

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

fn html_page(title: &str, heading: &str, color: &str, body: &str) -> impl IntoResponse {
    let html = format!(
        r#"<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title>
<style>*{{box-sizing:border-box;margin:0;padding:0}}
body{{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
background:#0f1117;color:#e2e8f0;display:flex;align-items:center;
justify-content:center;min-height:100vh}}
.card{{background:#1a1d27;border:1px solid #2d3148;border-radius:12px;
padding:48px;text-align:center;max-width:420px;width:100%}}
h1{{font-size:24px;color:{color};margin-bottom:12px}}
p{{color:#94a3b8;font-size:15px;line-height:1.6}}
a{{color:#818cf8;text-decoration:none}}a:hover{{text-decoration:underline}}</style>
</head><body><div class="card"><h1>{heading}</h1>{body}</div></body></html>"#
    );
    axum::response::Response::builder()
        .header("Content-Type", "text/html; charset=utf-8")
        .body(axum::body::Body::from(html))
        .unwrap()
}

/// GET /billing/success — shown after Stripe checkout completes
pub async fn checkout_success() -> impl IntoResponse {
    html_page(
        "Payment successful — bctx",
        "&#10003; Payment successful",
        "#4ade80",
        r#"<p>Your plan has been activated.<br><br>
<a href="https://betterctx.com/account">View your account →</a></p>"#,
    )
}

/// GET /billing/cancel — shown when user cancels Stripe checkout
pub async fn checkout_cancel() -> impl IntoResponse {
    html_page(
        "Checkout cancelled — bctx",
        "Checkout cancelled",
        "#f59e0b",
        r#"<p>No charge was made.<br><br><a href="https://betterctx.com/account">Back to your account →</a></p>"#,
    )
}

#[derive(Debug, Deserialize)]
pub struct CheckoutQuery {
    /// "free" | "beacon" | "studio" | "enterprise"
    pub tier: String,
}

/// Result of a billing change. Backward-compatible with the old `{url}` shape:
/// first-time checkout still returns `{url}`, so existing frontends that do
/// `if (data.url) redirect` keep working. In-place changes return `{status,
/// effective}` and the browser stays on the page.
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CheckoutResult {
    Redirect { url: String },
    Changed { status: String, effective: String },
}

// ── tier change decision (pure, unit-tested) ──────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BillingAction {
    /// First-time / re-onboard: send the user to a Stripe Checkout Session.
    Checkout,
    /// Existing subscriber moving up: swap price in place, prorated, immediate.
    Upgrade,
    /// Existing subscriber moving down: schedule the new price at period end.
    Downgrade,
    /// Existing subscriber dropping to Free: cancel at period end.
    Cancel,
    /// DB says a paid tier but Stripe has no live subscription (drift / comp /
    /// test→live carryover). The user asked for Free, so reconcile the DB to
    /// Free directly. Never reached while a live subscription exists.
    ForceFree,
    /// Requested tier equals current state — nothing to do.
    Noop,
    /// Enterprise is contact-sales, not self-serve purchasable.
    RejectEnterprise,
}

/// Decide what billing operation a tier request maps to, given the user's
/// current tier and whether they already have a live Stripe subscription.
///
/// `has_active_sub` reflects a *successful* Stripe lookup: it is only `false`
/// when Stripe confirmed there is no live subscription. A failed lookup errors
/// before reaching here, so a network blip can never produce a downgrade.
fn decide_action(current: Tier, requested: Tier, has_active_sub: bool) -> BillingAction {
    if requested == Tier::Enterprise {
        return BillingAction::RejectEnterprise;
    }
    if requested == Tier::Free {
        return if has_active_sub {
            // Real subscription exists → cancel it gracefully at period end.
            BillingAction::Cancel
        } else if current != Tier::Free {
            // Paid tier in our DB but no live subscription (drift / comp) →
            // reconcile to Free. Unreachable for a genuinely paying user.
            BillingAction::ForceFree
        } else {
            BillingAction::Noop
        };
    }
    // requested is a paid, self-serve tier (Beacon | Studio) from here.
    if !has_active_sub {
        return BillingAction::Checkout;
    }
    match requested.cmp(&current) {
        std::cmp::Ordering::Greater => BillingAction::Upgrade,
        std::cmp::Ordering::Less => BillingAction::Downgrade,
        std::cmp::Ordering::Equal => BillingAction::Noop,
    }
}

/// Stripe price ID for a self-serve paid tier. Enterprise/Free never reach here.
fn price_id_for_tier(tier: Tier) -> Result<String, AppError> {
    let var = match tier {
        Tier::Beacon => "BCTX_STRIPE_BEACON_PRICE",
        Tier::Studio => "BCTX_STRIPE_STUDIO_PRICE",
        _ => return Err(AppError(anyhow!("no self-serve price for tier {tier:?}"))),
    };
    std::env::var(var).map_err(|_| AppError(anyhow!("Stripe price ID not configured ({var})")))
}

// ── Stripe REST helpers ───────────────────────────────────────────────────────

/// Find the Stripe customer ID for an email. None means truly first-time.
async fn find_customer_id(
    client: &reqwest::Client,
    key: &str,
    email: &str,
) -> Result<Option<String>, AppError> {
    let resp = client
        .get("https://api.stripe.com/v1/customers")
        .basic_auth(key, Some(""))
        .query(&[("email", email), ("limit", "1")])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    let body: serde_json::Value = resp
        .json()
        .await
        .map_err(|e| AppError(anyhow!("invalid Stripe response: {e}")))?;
    Ok(body["data"][0]["id"].as_str().map(|s| s.to_string()))
}

/// An active subscription we can act on.
struct ActiveSub {
    sub_id: String,
    item_id: String,
    /// Attached subscription schedule id, if the sub is schedule-managed
    /// (e.g. a pending downgrade). Must be released before any direct change.
    schedule_id: Option<String>,
    /// True when the subscription is set to end at period end (cancel pending).
    cancel_at_period_end: bool,
    /// Unix-seconds timestamp of the current period end, if present.
    current_period_end: Option<i64>,
}

/// Find the customer's single live subscription. "Live" includes dunning states
/// (`past_due`/`unpaid`/`paused`) as well as `active`/`trialing`, so a customer
/// with a failing payment is still treated as having a real subscription —
/// never as "no subscription" (which would let the Free path hard-reset them).
/// Excludes terminal/half-formed states (`canceled`/`incomplete`/`incomplete_expired`).
async fn find_active_subscription(
    client: &reqwest::Client,
    key: &str,
    customer_id: &str,
) -> Result<Option<ActiveSub>, AppError> {
    let resp = client
        .get("https://api.stripe.com/v1/subscriptions")
        .basic_auth(key, Some(""))
        .query(&[
            ("customer", customer_id),
            ("status", "all"),
            ("limit", "10"),
        ])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    let body: serde_json::Value = resp
        .json()
        .await
        .map_err(|e| AppError(anyhow!("invalid Stripe response: {e}")))?;

    const LIVE_STATUSES: [&str; 5] = ["active", "trialing", "past_due", "unpaid", "paused"];
    let subs = body["data"].as_array().cloned().unwrap_or_default();
    for sub in subs {
        let status = sub["status"].as_str().unwrap_or("");
        if !LIVE_STATUSES.contains(&status) {
            continue;
        }
        let sub_id = sub["id"].as_str().unwrap_or("").to_string();
        let item = &sub["items"]["data"][0];
        let item_id = item["id"].as_str().unwrap_or("").to_string();
        let price = item["price"]["id"].as_str().unwrap_or("").to_string();
        let schedule_id = sub["schedule"].as_str().map(|s| s.to_string());
        let cancel_at_period_end = sub["cancel_at_period_end"].as_bool().unwrap_or(false);
        let current_period_end = sub["current_period_end"].as_i64();
        if !sub_id.is_empty() && !item_id.is_empty() && !price.is_empty() {
            return Ok(Some(ActiveSub {
                sub_id,
                item_id,
                schedule_id,
                cancel_at_period_end,
                current_period_end,
            }));
        }
    }
    Ok(None)
}

/// Release a subscription schedule so the subscription returns to normal
/// management and direct updates (price swap, cancel) become allowed again.
/// Releasing discards any pending scheduled phase (e.g. a queued downgrade),
/// which is the desired behavior when the user is making a new change.
async fn release_schedule(
    client: &reqwest::Client,
    key: &str,
    schedule_id: &str,
) -> Result<(), AppError> {
    let url = format!("https://api.stripe.com/v1/subscription_schedules/{schedule_id}/release");
    let resp = client
        .post(&url)
        .basic_auth(key, Some(""))
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    if !resp.status().is_success() {
        let body = resp.text().await.unwrap_or_default();
        return Err(AppError(anyhow!("Stripe schedule release error: {body}")));
    }
    Ok(())
}

/// Immediate, prorated upgrade: swap the subscription item's price in place.
async fn upgrade_subscription(
    client: &reqwest::Client,
    key: &str,
    sub_id: &str,
    item_id: &str,
    new_price: &str,
) -> Result<(), AppError> {
    let url = format!("https://api.stripe.com/v1/subscriptions/{sub_id}");
    let resp = client
        .post(&url)
        .basic_auth(key, Some(""))
        .form(&[
            ("items[0][id]", item_id),
            ("items[0][price]", new_price),
            ("proration_behavior", "create_prorations"),
            ("payment_behavior", "error_if_incomplete"),
        ])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    if !resp.status().is_success() {
        let body = resp.text().await.unwrap_or_default();
        return Err(AppError(anyhow!("Stripe upgrade error: {body}")));
    }
    Ok(())
}

/// Scheduled downgrade: convert the subscription to a schedule whose second
/// phase (the new, lower price) starts at the current period end. The customer
/// keeps the higher tier until renewal; Stripe then fires
/// `customer.subscription.updated` with the new price, which the webhook applies.
async fn downgrade_subscription_at_period_end(
    client: &reqwest::Client,
    key: &str,
    sub_id: &str,
    new_price: &str,
) -> Result<(), AppError> {
    // Step A: create a schedule from the subscription — Stripe pre-fills phase 0.
    let create = client
        .post("https://api.stripe.com/v1/subscription_schedules")
        .basic_auth(key, Some(""))
        .form(&[("from_subscription", sub_id)])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    if !create.status().is_success() {
        let body = create.text().await.unwrap_or_default();
        return Err(AppError(anyhow!("Stripe schedule create error: {body}")));
    }
    let sched: serde_json::Value = create
        .json()
        .await
        .map_err(|e| AppError(anyhow!("invalid Stripe response: {e}")))?;

    let schedule_id = sched["id"]
        .as_str()
        .ok_or_else(|| AppError(anyhow!("no schedule id in Stripe response")))?
        .to_string();
    let phase0 = &sched["phases"][0];
    let phase0_start = phase0["start_date"]
        .as_i64()
        .ok_or_else(|| AppError(anyhow!("schedule phase missing start_date")))?;
    let phase0_end = phase0["end_date"]
        .as_i64()
        .ok_or_else(|| AppError(anyhow!("schedule phase missing end_date")))?;
    let phase0_price = phase0["items"][0]["price"]
        .as_str()
        .ok_or_else(|| AppError(anyhow!("schedule phase missing price")))?
        .to_string();

    let (start_s, end_s) = (phase0_start.to_string(), phase0_end.to_string());

    // Step B: re-send phase 0 verbatim and append phase 1 with the new price.
    let url = format!("https://api.stripe.com/v1/subscription_schedules/{schedule_id}");
    let update = client
        .post(&url)
        .basic_auth(key, Some(""))
        .form(&[
            ("end_behavior", "release"),
            ("proration_behavior", "none"),
            ("phases[0][items][0][price]", phase0_price.as_str()),
            ("phases[0][start_date]", start_s.as_str()),
            ("phases[0][end_date]", end_s.as_str()),
            ("phases[1][items][0][price]", new_price),
            ("phases[1][iterations]", "1"),
        ])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    if !update.status().is_success() {
        let body = update.text().await.unwrap_or_default();
        return Err(AppError(anyhow!("Stripe schedule update error: {body}")));
    }
    Ok(())
}

/// Cancel at period end (not an immediate delete). The terminal
/// `customer.subscription.deleted` event lands at period end → tier = free.
async fn cancel_subscription_at_period_end(
    client: &reqwest::Client,
    key: &str,
    sub_id: &str,
) -> Result<(), AppError> {
    let url = format!("https://api.stripe.com/v1/subscriptions/{sub_id}");
    let resp = client
        .post(&url)
        .basic_auth(key, Some(""))
        .form(&[("cancel_at_period_end", "true")])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    if !resp.status().is_success() {
        let body = resp.text().await.unwrap_or_default();
        return Err(AppError(anyhow!("Stripe cancel error: {body}")));
    }
    Ok(())
}

/// POST /billing/checkout?tier=beacon
///
/// Single entry point for all self-serve tier changes. The server inspects the
/// user's current Stripe state and routes to the right operation so a customer
/// never ends up with two subscriptions:
///   - first time (no active sub) → Stripe Checkout Session (returns `{url}`)
///   - upgrade   → immediate, prorated price swap
///   - downgrade → scheduled at period end
///   - free      → cancel at period end
///   - enterprise → rejected (contact sales)
///
/// Requires env vars:
///   BCTX_STRIPE_SECRET_KEY        — Stripe secret key (sk_live_... or sk_test_...)
///   BCTX_STRIPE_BEACON_PRICE      — Stripe price ID for Beacon tier
///   BCTX_STRIPE_STUDIO_PRICE      — Stripe price ID for Studio tier
///   BCTX_BASE_URL                 — base URL for success/cancel redirects
pub async fn create_checkout(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    Query(params): Query<CheckoutQuery>,
) -> Result<impl IntoResponse, AppError> {
    // Strict allowlist — guard against typos silently becoming a Free/cancel.
    if !matches!(
        params.tier.as_str(),
        "free" | "beacon" | "studio" | "enterprise"
    ) {
        return Err(AppError(anyhow!("unknown tier: {}", params.tier)));
    }
    let requested = Tier::parse_tier(&params.tier);

    if requested == Tier::Enterprise {
        return Err(AppError(anyhow!(
            "Enterprise is not self-serve — please contact sales at https://betterctx.com/contact"
        )));
    }

    let stripe_key = std::env::var("BCTX_STRIPE_SECRET_KEY").map_err(|_| {
        AppError(anyhow!(
            "Stripe not configured: missing BCTX_STRIPE_SECRET_KEY"
        ))
    })?;

    let user = state
        .db
        .get_user(&user_id)
        .ok_or_else(|| AppError(anyhow!("user not found")))?;
    let current = Tier::parse_tier(&user.tier);

    let client = reqwest::Client::new();
    let customer_id = find_customer_id(&client, &stripe_key, &user.email).await?;
    let active = match &customer_id {
        Some(cid) => find_active_subscription(&client, &stripe_key, cid).await?,
        None => None,
    };

    match decide_action(current, requested, active.is_some()) {
        BillingAction::RejectEnterprise => Err(AppError(anyhow!(
            "Enterprise is not self-serve — please contact sales at https://betterctx.com/contact"
        ))),
        BillingAction::Noop => Ok((
            StatusCode::OK,
            Json(CheckoutResult::Changed {
                status: "noop".into(),
                effective: "none".into(),
            }),
        )),
        BillingAction::ForceFree => {
            // No live Stripe subscription to cancel — just reconcile the DB tier.
            state
                .db
                .change_user_tier(&user_id, "free", "downgrade_to_free")?;
            tracing::info!(
                user_id,
                prior_tier = user.tier,
                "tier reset to free (no live subscription)"
            );
            Ok((
                StatusCode::OK,
                Json(CheckoutResult::Changed {
                    status: "freed".into(),
                    effective: "immediate".into(),
                }),
            ))
        }
        BillingAction::Cancel => {
            let sub = active.expect("cancel requires an active sub");
            // A schedule-managed subscription rejects direct cancel — release it first.
            if let Some(sched) = &sub.schedule_id {
                release_schedule(&client, &stripe_key, sched).await?;
            }
            cancel_subscription_at_period_end(&client, &stripe_key, &sub.sub_id).await?;
            Ok((
                StatusCode::OK,
                Json(CheckoutResult::Changed {
                    status: "canceled".into(),
                    effective: "period_end".into(),
                }),
            ))
        }
        BillingAction::Upgrade => {
            let sub = active.expect("upgrade requires an active sub");
            // Drop any pending downgrade schedule before swapping the price.
            if let Some(sched) = &sub.schedule_id {
                release_schedule(&client, &stripe_key, sched).await?;
            }
            let new_price = price_id_for_tier(requested)?;
            upgrade_subscription(&client, &stripe_key, &sub.sub_id, &sub.item_id, &new_price)
                .await?;
            state
                .db
                .change_user_tier(&user_id, &params.tier, "upgrade")?;
            tracing::info!(user_id, tier = params.tier, "subscription upgraded");
            Ok((
                StatusCode::OK,
                Json(CheckoutResult::Changed {
                    status: "upgraded".into(),
                    effective: "immediate".into(),
                }),
            ))
        }
        BillingAction::Downgrade => {
            let sub = active.expect("downgrade requires an active sub");
            // Replace any existing pending schedule with the new one.
            if let Some(sched) = &sub.schedule_id {
                release_schedule(&client, &stripe_key, sched).await?;
            }
            let new_price = price_id_for_tier(requested)?;
            downgrade_subscription_at_period_end(&client, &stripe_key, &sub.sub_id, &new_price)
                .await?;
            tracing::info!(
                user_id,
                tier = params.tier,
                "subscription downgrade scheduled"
            );
            Ok((
                StatusCode::OK,
                Json(CheckoutResult::Changed {
                    status: "downgraded".into(),
                    effective: "period_end".into(),
                }),
            ))
        }
        BillingAction::Checkout => {
            let price_id = price_id_for_tier(requested)?;
            let success_url = format!(
                "{}/billing/success?session_id={{CHECKOUT_SESSION_ID}}",
                state.base_url
            );
            let cancel_url = format!("{}/billing/cancel", state.base_url);

            let form = [
                ("mode", "subscription"),
                ("customer_email", user.email.as_str()),
                ("success_url", success_url.as_str()),
                ("cancel_url", cancel_url.as_str()),
                ("line_items[0][price]", price_id.as_str()),
                ("line_items[0][quantity]", "1"),
                ("metadata[user_id]", user_id.as_str()),
                ("metadata[price_id]", price_id.as_str()),
                // Propagate identity onto the subscription so the
                // subscription.updated/deleted webhooks can resolve the user.
                ("subscription_data[metadata][user_id]", user_id.as_str()),
                ("subscription_data[metadata][email]", user.email.as_str()),
            ];

            let resp = client
                .post("https://api.stripe.com/v1/checkout/sessions")
                .basic_auth(&stripe_key, Some(""))
                .form(&form)
                .send()
                .await
                .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;

            if !resp.status().is_success() {
                let body = resp.text().await.unwrap_or_default();
                return Err(AppError(anyhow!("Stripe API error: {body}")));
            }

            let session: serde_json::Value = resp
                .json()
                .await
                .map_err(|e| AppError(anyhow!("invalid Stripe response: {e}")))?;

            let url = session["url"]
                .as_str()
                .ok_or_else(|| AppError(anyhow!("no url in Stripe checkout session response")))?
                .to_string();

            tracing::info!(user_id, tier = params.tier, "checkout session created");
            Ok((StatusCode::OK, Json(CheckoutResult::Redirect { url })))
        }
    }
}

#[derive(Debug, Serialize)]
pub struct PortalResponse {
    pub url: String,
}

/// POST /billing/portal
///
/// Creates a Stripe Customer Portal session so the user can manage their
/// subscription (cancel, update payment method, view invoices).
pub async fn create_portal(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
) -> Result<impl IntoResponse, AppError> {
    let stripe_key = std::env::var("BCTX_STRIPE_SECRET_KEY").map_err(|_| {
        AppError(anyhow!(
            "Stripe not configured: missing BCTX_STRIPE_SECRET_KEY"
        ))
    })?;

    let user = state
        .db
        .get_user(&user_id)
        .ok_or_else(|| AppError(anyhow!("user not found")))?;

    let frontend_base =
        std::env::var("BCTX_FRONTEND_URL").unwrap_or_else(|_| "https://betterctx.com".to_string());
    let return_url = format!("{frontend_base}/account");
    let client = reqwest::Client::new();

    // First: find the Stripe customer ID by email (reqwest encodes query params automatically)
    let customer_resp = client
        .get("https://api.stripe.com/v1/customers")
        .basic_auth(&stripe_key, Some(""))
        .query(&[("email", user.email.as_str()), ("limit", "1")])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;

    let customers: serde_json::Value = customer_resp
        .json()
        .await
        .map_err(|e| AppError(anyhow!("invalid Stripe response: {e}")))?;

    let customer_id = customers["data"][0]["id"]
        .as_str()
        .ok_or_else(|| AppError(anyhow!("no Stripe customer found for this account")))?
        .to_string();

    // Then: create the portal session
    let portal_resp = client
        .post("https://api.stripe.com/v1/billing_portal/sessions")
        .basic_auth(&stripe_key, Some(""))
        .form(&[
            ("customer", customer_id.as_str()),
            ("return_url", return_url.as_str()),
        ])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;

    if !portal_resp.status().is_success() {
        let body = portal_resp.text().await.unwrap_or_default();
        return Err(AppError(anyhow!("Stripe portal error: {body}")));
    }

    let session: serde_json::Value = portal_resp
        .json()
        .await
        .map_err(|e| AppError(anyhow!("invalid Stripe portal response: {e}")))?;

    let url = session["url"]
        .as_str()
        .ok_or_else(|| AppError(anyhow!("no url in Stripe portal session response")))?
        .to_string();

    tracing::info!(user_id, "billing portal session created");
    Ok((StatusCode::OK, Json(PortalResponse { url })))
}

#[derive(Debug, Serialize)]
pub struct BillingStatus {
    pub tier: String,
    /// True when the subscription is scheduled to cancel at period end.
    pub cancel_at_period_end: bool,
    /// Unix-seconds timestamp of the period end (when the cancel takes effect).
    pub period_end: Option<i64>,
}

/// GET /billing/status
///
/// Lightweight read of the user's subscription cancellation state, so the UI can
/// show "Cancels on <date>" with a Resume option. Degrades gracefully: any Stripe
/// hiccup just yields `cancel_at_period_end = false` rather than failing the page.
pub async fn billing_status(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
) -> Result<impl IntoResponse, AppError> {
    let user = state
        .db
        .get_user(&user_id)
        .ok_or_else(|| AppError(anyhow!("user not found")))?;
    let tier = user.tier.clone();

    let stripe_key = match std::env::var("BCTX_STRIPE_SECRET_KEY") {
        Ok(k) => k,
        Err(_) => {
            return Ok(Json(BillingStatus {
                tier,
                cancel_at_period_end: false,
                period_end: None,
            }))
        }
    };

    let client = reqwest::Client::new();
    let customer_id = find_customer_id(&client, &stripe_key, &user.email)
        .await
        .unwrap_or(None);
    let sub = match &customer_id {
        Some(cid) => find_active_subscription(&client, &stripe_key, cid)
            .await
            .unwrap_or(None),
        None => None,
    };

    let (cancel_at_period_end, period_end) = match sub {
        Some(s) => (s.cancel_at_period_end, s.current_period_end),
        None => (false, None),
    };

    Ok(Json(BillingStatus {
        tier,
        cancel_at_period_end,
        period_end,
    }))
}

/// Clear a pending cancellation: set `cancel_at_period_end = false`.
async fn resume_subscription(
    client: &reqwest::Client,
    key: &str,
    sub_id: &str,
) -> Result<(), AppError> {
    let url = format!("https://api.stripe.com/v1/subscriptions/{sub_id}");
    let resp = client
        .post(&url)
        .basic_auth(key, Some(""))
        .form(&[("cancel_at_period_end", "false")])
        .send()
        .await
        .map_err(|e| AppError(anyhow!("Stripe API request failed: {e}")))?;
    if !resp.status().is_success() {
        let body = resp.text().await.unwrap_or_default();
        return Err(AppError(anyhow!("Stripe resume error: {body}")));
    }
    Ok(())
}

/// POST /billing/resume — undo a scheduled cancellation, keeping the plan active.
pub async fn billing_resume(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
) -> Result<impl IntoResponse, AppError> {
    let stripe_key = std::env::var("BCTX_STRIPE_SECRET_KEY").map_err(|_| {
        AppError(anyhow!(
            "Stripe not configured: missing BCTX_STRIPE_SECRET_KEY"
        ))
    })?;
    let user = state
        .db
        .get_user(&user_id)
        .ok_or_else(|| AppError(anyhow!("user not found")))?;

    let client = reqwest::Client::new();
    let customer_id = find_customer_id(&client, &stripe_key, &user.email)
        .await?
        .ok_or_else(|| AppError(anyhow!("no Stripe customer for this account")))?;
    let sub = find_active_subscription(&client, &stripe_key, &customer_id)
        .await?
        .ok_or_else(|| AppError(anyhow!("no subscription to resume")))?;

    resume_subscription(&client, &stripe_key, &sub.sub_id).await?;
    tracing::info!(user_id, "subscription cancellation cleared (resumed)");
    Ok((
        StatusCode::OK,
        Json(CheckoutResult::Changed {
            status: "resumed".into(),
            effective: "immediate".into(),
        }),
    ))
}

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

    #[test]
    fn enterprise_is_rejected() {
        assert_eq!(
            decide_action(Tier::Beacon, Tier::Enterprise, true),
            BillingAction::RejectEnterprise
        );
        assert_eq!(
            decide_action(Tier::Free, Tier::Enterprise, false),
            BillingAction::RejectEnterprise
        );
    }

    #[test]
    fn first_time_buyer_checks_out() {
        assert_eq!(
            decide_action(Tier::Free, Tier::Beacon, false),
            BillingAction::Checkout
        );
    }

    #[test]
    fn paid_tier_without_active_sub_reonboards() {
        // DB says paid but Stripe has no active sub → re-onboard via checkout, not 500.
        assert_eq!(
            decide_action(Tier::Beacon, Tier::Studio, false),
            BillingAction::Checkout
        );
    }

    #[test]
    fn moving_up_is_an_upgrade() {
        assert_eq!(
            decide_action(Tier::Beacon, Tier::Studio, true),
            BillingAction::Upgrade
        );
    }

    #[test]
    fn moving_down_is_a_downgrade() {
        assert_eq!(
            decide_action(Tier::Studio, Tier::Beacon, true),
            BillingAction::Downgrade
        );
    }

    #[test]
    fn dropping_to_free_with_live_sub_cancels() {
        // A genuinely paying user (live sub) always gets graceful cancel —
        // never a hard reset.
        assert_eq!(
            decide_action(Tier::Studio, Tier::Free, true),
            BillingAction::Cancel
        );
        assert_eq!(
            decide_action(Tier::Beacon, Tier::Free, true),
            BillingAction::Cancel
        );
    }

    #[test]
    fn paid_tier_without_sub_reconciles_to_free() {
        // DB says paid but Stripe has no live subscription (drift / comp) and the
        // user asked for Free → reset the DB tier. Only reachable with no sub.
        assert_eq!(
            decide_action(Tier::Beacon, Tier::Free, false),
            BillingAction::ForceFree
        );
        assert_eq!(
            decide_action(Tier::Studio, Tier::Free, false),
            BillingAction::ForceFree
        );
    }

    #[test]
    fn free_with_no_sub_is_noop() {
        assert_eq!(
            decide_action(Tier::Free, Tier::Free, false),
            BillingAction::Noop
        );
    }

    #[test]
    fn same_tier_is_noop() {
        assert_eq!(
            decide_action(Tier::Beacon, Tier::Beacon, true),
            BillingAction::Noop
        );
    }
}