prlens 0.1.1

One queue for all your PRs — aggregates GitHub and Bitbucket review requests into a single interactive view
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use reqwest::Client;
use std::path::PathBuf;

use super::{AuthStatus, Provider, ProviderError};
use crate::cache;
use crate::config::BitbucketConfig;
use crate::models::{
    PrIdentifier, PrState, PullRequest, ReviewStatus, Reviewer, ReviewerState, User,
};

// ── Serde structs: Bitbucket Data Center API response types ──────────────────

/// Custom deserializer for Bitbucket Data Center epoch-millisecond timestamps.
/// Data Center timestamps are i64 Unix epoch milliseconds (e.g. 1731663000000).
/// Cloud uses RFC3339 strings — handled natively by chrono.
fn deserialise_epoch_ms<'de, D>(d: D) -> Result<DateTime<Utc>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    let ms = i64::deserialize(d)?;
    Ok(DateTime::from_timestamp(ms / 1000, 0).unwrap_or_default())
}

#[derive(serde::Deserialize)]
struct DataCenterPage {
    values: Vec<DataCenterPr>,
    #[serde(rename = "isLastPage")]
    is_last_page: bool,
    #[serde(rename = "nextPageStart")]
    next_page_start: Option<u64>,
}

#[derive(serde::Deserialize)]
struct DataCenterPr {
    id: u64,
    title: String,
    links: DcLinks,
    author: DcParticipant,
    #[serde(rename = "fromRef")]
    from_ref: DcRef,
    #[serde(rename = "toRef")]
    to_ref: DcRef,
    reviewers: Vec<DcReviewer>,
    #[serde(rename = "createdDate", deserialize_with = "deserialise_epoch_ms")]
    created_date: DateTime<Utc>,
    #[serde(rename = "updatedDate", deserialize_with = "deserialise_epoch_ms")]
    updated_date: DateTime<Utc>,
    properties: Option<DcProperties>,
}

#[derive(serde::Deserialize)]
struct DcLinks {
    #[serde(rename = "self")]
    self_links: Vec<DcHref>,
}

#[derive(serde::Deserialize)]
struct DcHref {
    href: String,
}

#[derive(serde::Deserialize)]
struct DcParticipant {
    user: DcUser,
}

#[derive(serde::Deserialize)]
struct DcUser {
    slug: String,
    #[serde(rename = "displayName")]
    display_name: String,
}

#[derive(serde::Deserialize)]
struct DcRef {
    #[serde(rename = "displayId")]
    display_id: String,
    repository: DcRepository,
}

#[derive(serde::Deserialize)]
struct DcRepository {
    slug: String,
    project: DcProject,
}

#[derive(serde::Deserialize)]
struct DcProject {
    key: String,
}

#[derive(serde::Deserialize)]
struct DcReviewer {
    user: DcUser,
    approved: bool,
    status: String,
}

#[derive(serde::Deserialize)]
struct DcProperties {
    #[serde(rename = "commentCount")]
    comment_count: Option<u32>,
}

// ── Serde structs: Bitbucket Cloud API response types ────────────────────────

#[derive(serde::Deserialize)]
struct CloudUserResponse {
    uuid: String,
}

#[derive(serde::Deserialize)]
struct CloudPrPage {
    values: Vec<CloudPr>,
    next: Option<String>,
    #[allow(dead_code)]
    size: Option<u64>,
}

#[derive(serde::Deserialize)]
struct CloudPr {
    id: u64,
    title: String,
    links: CloudLinks,
    author: CloudAuthor,
    source: CloudEndpoint,
    destination: CloudEndpoint,
    reviewers: Vec<CloudReviewer>,
    participants: Vec<CloudParticipant>,
    /// RFC3339 — chrono deserializes this natively; no annotation needed
    created_on: DateTime<Utc>,
    /// RFC3339 — chrono deserializes this natively; no annotation needed
    updated_on: DateTime<Utc>,
    #[serde(rename = "comment_count")]
    comment_count: Option<u32>,
    /// Draft field — may be absent in older API responses; defaults to false
    #[serde(default)]
    draft: Option<bool>,
}

#[derive(serde::Deserialize)]
struct CloudLinks {
    html: CloudHref,
}

#[derive(serde::Deserialize)]
struct CloudHref {
    href: String,
}

#[derive(serde::Deserialize)]
struct CloudAuthor {
    account_id: Option<String>,
    display_name: String,
    nickname: Option<String>,
}

#[derive(serde::Deserialize)]
struct CloudEndpoint {
    branch: CloudBranch,
    repository: CloudRepository,
}

#[derive(serde::Deserialize)]
struct CloudBranch {
    name: String,
}

#[derive(serde::Deserialize)]
struct CloudRepository {
    slug: String,
    workspace: CloudWorkspace,
    #[serde(rename = "full_name")]
    full_name: String,
}

#[derive(serde::Deserialize)]
struct CloudWorkspace {
    slug: String,
}

#[derive(serde::Deserialize)]
struct CloudReviewer {
    account_id: String,
    display_name: String,
    approved: Option<bool>,
}

#[derive(serde::Deserialize)]
struct CloudParticipant {
    role: String,
    approved: bool,
    state: Option<String>,
    user: CloudParticipantUser,
}

#[derive(serde::Deserialize)]
struct CloudParticipantUser {
    account_id: Option<String>,
    display_name: String,
    nickname: Option<String>,
}

// ── Reviewer state mapping ────────────────────────────────────────────────────

/// Map Bitbucket reviewer flags to ReviewerState.
///
/// Data Center: `approved` bool + `status` string ("APPROVED", "NEEDS_WORK", "UNAPPROVED")
/// Cloud: `approved` bool from participant entry + `state` string
fn map_reviewer_state(approved: bool, status: &str) -> ReviewerState {
    match (approved, status) {
        (true, _) => ReviewerState::Approved,
        (false, "needs_work") | (false, "NEEDS_WORK") | (false, "NEEDS-WORK") => {
            ReviewerState::ChangesRequested
        }
        _ => ReviewerState::Pending,
    }
}

// ── Constants ─────────────────────────────────────────────────────────────────

/// Default base URL for Bitbucket Cloud. No trailing `/2.0` — API path segments
/// are appended by each caller (e.g. `{CLOUD_BASE_URL}/2.0/user`).
/// Users setting `base_url` in config should use this value (without `/2.0`).
const CLOUD_BASE_URL: &str = "https://api.bitbucket.org";

// ── BitbucketMode ─────────────────────────────────────────────────────────────

/// Bitbucket deployment mode detected from the configured base URL.
/// Cloud uses `api.bitbucket.org` with Basic auth (email:token).
/// DataCenter uses a self-hosted URL with Bearer auth.
#[derive(Debug, Clone, PartialEq)]
pub enum BitbucketMode {
    /// Bitbucket Cloud (SaaS). Base URL: api.bitbucket.org
    Cloud,
    /// Bitbucket Data Center (self-hosted). Custom base URL.
    DataCenter,
}

impl BitbucketMode {
    /// Detect the deployment mode from the effective base URL string.
    /// Rule: URL containing "api.bitbucket.org" → Cloud; anything else → DataCenter.
    pub fn from_base_url(url: &str) -> Self {
        if url.contains("api.bitbucket.org") {
            BitbucketMode::Cloud
        } else {
            BitbucketMode::DataCenter
        }
    }
}

// ── BitbucketProvider ─────────────────────────────────────────────────────────

/// BitbucketProvider fetches PRs from Bitbucket (Cloud or Data Center) via token auth.
///
/// Auth: BB_TOKEN env var first, then [bitbucket] token in config (D-01, D-02, D-03)
/// Cache: ~/.cache/prlens/bitbucket.json with a 60-second TTL (ARCH-04)
/// Mode: Detected from base_url at construction time; Cloud and Data Center dispatch separately.
pub struct BitbucketProvider {
    config: BitbucketConfig,
    /// Override base URL — None in production, Some(uri) in tests (wiremock).
    base_url: Option<String>,
    /// Cache file path — computed at construction time.
    cache_path: PathBuf,
    /// Deployment mode — detected from effective base URL at construction time.
    mode: BitbucketMode,
}

impl BitbucketProvider {
    /// Production constructor. Cache path computed from dirs::cache_dir() at construction time.
    pub fn new(config: BitbucketConfig) -> Self {
        let base_url_str = Self::resolve_base_url(&config)
            .unwrap_or_else(|| CLOUD_BASE_URL.to_string());
        let mode = BitbucketMode::from_base_url(&base_url_str);
        let cache_path = dirs::cache_dir()
            .unwrap_or_else(|| PathBuf::from("/tmp"))
            .join("prlens")
            .join("bitbucket.json");
        Self {
            config,
            base_url: None,
            cache_path,
            mode,
        }
    }

    /// Test constructor. Accepts a wiremock base URL and an isolated cache path.
    /// Mode is detected from the provided base_url parameter.
    pub fn new_with_base_url(
        config: BitbucketConfig,
        base_url: String,
        cache_path: PathBuf,
    ) -> Self {
        let mode = BitbucketMode::from_base_url(&base_url);
        Self {
            config,
            base_url: Some(base_url),
            cache_path,
            mode,
        }
    }

    /// Test constructor with explicit mode override.
    /// Use this when the base_url is a wiremock localhost URI (which would otherwise
    /// be detected as DataCenter), but you want to test the Cloud path.
    pub fn new_with_mode(
        config: BitbucketConfig,
        base_url: String,
        cache_path: PathBuf,
        mode: BitbucketMode,
    ) -> Self {
        Self {
            config,
            base_url: Some(base_url),
            cache_path,
            mode,
        }
    }

    /// Validate and return the effective cache path for this provider instance.
    /// Creates parent directories as needed.
    fn effective_cache_path(&self) -> Result<PathBuf, ProviderError> {
        if let Some(parent) = self.cache_path.parent() {
            if !parent.exists() {
                if let Err(e) = std::fs::create_dir_all(parent) {
                    return Err(ProviderError::IoError {
                        provider: "bitbucket".to_string(),
                        message: format!(
                            "Cannot create cache directory {:?}: {}",
                            parent, e
                        ),
                    });
                }
            }
        }
        Ok(self.cache_path.clone())
    }

    /// Resolve the Bitbucket token from environment variable or config field.
    ///
    /// Resolution order (D-01):
    ///   1. BB_TOKEN env var (D-03)
    ///   2. config.token field (D-04)
    ///
    /// SECURITY: The token value is NEVER logged at any tracing level.
    /// Only "token resolved from X" or "token not found" are logged.
    pub fn resolve_token(config: &BitbucketConfig) -> Option<String> {
        // D-03: BB_TOKEN env var takes priority
        if let Ok(token) = std::env::var("BB_TOKEN") {
            if !token.is_empty() {
                tracing::debug!("Bitbucket token resolved from BB_TOKEN env var");
                return Some(token);
            }
        }
        // D-04: config field fallback
        if let Some(ref token) = config.token {
            if !token.is_empty() {
                tracing::debug!("Bitbucket token resolved from config [bitbucket] token field");
                return Some(token.clone());
            }
        }
        tracing::debug!(
            "Bitbucket token not found: BB_TOKEN unset or empty, config token absent"
        );
        None
    }

    /// Resolve the Bitbucket server base URL.
    /// Priority: BB_SERVER_URL env var → [bitbucket] base_url config → None (caller supplies Cloud default)
    pub fn resolve_base_url(config: &BitbucketConfig) -> Option<String> {
        if let Ok(url) = std::env::var("BB_SERVER_URL") {
            if !url.is_empty() {
                tracing::debug!("Bitbucket base URL resolved from BB_SERVER_URL env var");
                return Some(url);
            }
        }
        if let Some(ref url) = config.base_url {
            if !url.is_empty() {
                tracing::debug!("Bitbucket base URL resolved from config [bitbucket] base_url");
                return Some(url.clone());
            }
        }
        None
    }

    /// Get the effective base URL for API calls.
    /// In tests: self.base_url (wiremock URI, highest priority).
    /// In production: BB_SERVER_URL env var → config base_url → Cloud default.
    fn effective_base_url(&self) -> String {
        if let Some(ref url) = self.base_url {
            return url.clone();
        }
        Self::resolve_base_url(&self.config)
            .unwrap_or_else(|| CLOUD_BASE_URL.to_string())
    }

    /// Validate that a base URL uses HTTPS (SSRF mitigation — T-4-05).
    /// Tests use http://localhost:... which must be allowed; only reject non-localhost http.
    fn validate_base_url_https(base: &str) -> Result<(), ProviderError> {
        // Allow http:// for localhost/127.0.0.1 (wiremock test servers)
        if base.starts_with("http://") {
            let after_scheme = &base["http://".len()..];
            let host = after_scheme.split('/').next().unwrap_or("").split(':').next().unwrap_or("");
            if host == "localhost" || host == "127.0.0.1" || host == "::1" {
                return Ok(());
            }
            return Err(ProviderError::ApiError {
                provider: "bitbucket".to_string(),
                status: 0,
                message: "base_url must use HTTPS".to_string(),
            });
        }
        Ok(())
    }


    /// Returns true when `cursor` shares the same scheme+host as `base` (SSRF guard for pagination).
    fn same_origin(base: &str, cursor: &str) -> bool {
        fn origin(url: &str) -> &str {
            // scheme://host[:port] — everything up to the third slash
            let rest = url.splitn(3, '/').collect::<Vec<_>>();
            if rest.len() >= 2 { url.get(..url.len() - rest.last().map_or(0, |s| s.len())).unwrap_or(url) } else { url }
        }
        origin(base) == origin(cursor)
    }

    /// Fetch PRs from Bitbucket Data Center using the dashboard endpoint.
    ///
    /// Endpoint: GET {base_url}/rest/api/1.0/dashboard/pull-requests
    /// Auth: Authorization: Bearer {token}
    /// Pagination: isLastPage / nextPageStart cursor model
    async fn fetch_data_center(&self, token: &str) -> Result<Vec<PullRequest>, ProviderError> {
        let base = self.effective_base_url();
        Self::validate_base_url_https(&base)?;

        let url = format!("{}/rest/api/1.0/dashboard/pull-requests", base);
        let client = Client::new();
        let mut prs: Vec<PullRequest> = Vec::new();
        let mut start = 0u64;

        loop {
            let resp = client
                .get(&url)
                .header("Authorization", format!("Bearer {}", token))
                .query(&[
                    ("role", "REVIEWER"),
                    ("state", "OPEN"),
                    ("limit", "100"),
                    ("start", &start.to_string()),
                ])
                .send()
                .await
                .map_err(|e| ProviderError::ApiError {
                    provider: "bitbucket".to_string(),
                    status: 0,
                    message: e.to_string(),
                })?;

            if !resp.status().is_success() {
                let status = resp.status().as_u16();
                let message = resp.text().await.unwrap_or_default();
                return Err(ProviderError::ApiError {
                    provider: "bitbucket".to_string(),
                    status,
                    message,
                });
            }

            let page: DataCenterPage = resp.json().await.map_err(|e| ProviderError::ParseError {
                provider: "bitbucket".to_string(),
                message: e.to_string(),
            })?;

            for dc_pr in page.values {
                prs.push(normalize_dc_pr(dc_pr, "bitbucket"));
            }

            if page.is_last_page {
                break;
            }
            match page.next_page_start {
                Some(next) => start = next,
                None => { tracing::warn!("Bitbucket DC: isLastPage=false but nextPageStart absent — stopping to avoid infinite loop"); break; }
            }
        }

        Ok(prs)
    }

    /// Fetch PRs from Bitbucket Cloud using workspace fan-out strategy.
    ///
    /// Cloud does NOT have a global reviewer endpoint (Pattern 4 — RESEARCH.md).
    /// Strategy:
    ///   1. GET /2.0/user → extract uuid for q-filter
    ///   2. For each repo in watch_repos OR enumerate workspace repos
    ///   3. Query each repo: GET /2.0/repositories/{ws}/{slug}/pullrequests?q=reviewers.uuid={uuid}
    ///   4. Deduplicate and return
    ///
    /// Auth: Basic auth with username:token (username is the Atlassian account email)
    async fn fetch_cloud(&self, token: &str) -> Result<Vec<PullRequest>, ProviderError> {
        // Step A — Require username for Cloud
        let username = self.config.username.as_ref().ok_or_else(|| {
            ProviderError::AuthMissing {
                provider: "bitbucket".to_string(),
                reason: "Bitbucket Cloud requires [bitbucket] username = \"your@atlassian.email\" \
                         in config.toml. Set this to your Atlassian account email (for API tokens) \
                         or your Bitbucket username (for app passwords, deprecated June 2026)."
                    .to_string(),
            }
        })?;

        let base = self.effective_base_url();
        Self::validate_base_url_https(&base)?;

        let client = Client::new();

        // Step B — Get user UUID for reviewers.uuid q-filter
        let user_resp = client
            .get(format!("{}/2.0/user", base))
            .basic_auth(username, Some(token))
            .send()
            .await
            .map_err(|e| ProviderError::ApiError {
                provider: "bitbucket".to_string(),
                status: 0,
                message: e.to_string(),
            })?;

        if !user_resp.status().is_success() {
            let status = user_resp.status().as_u16();
            let message = user_resp.text().await.unwrap_or_default();
            return Err(ProviderError::ApiError {
                provider: "bitbucket".to_string(),
                status,
                message,
            });
        }

        let user_data: CloudUserResponse =
            user_resp.json().await.map_err(|e| ProviderError::ParseError {
                provider: "bitbucket".to_string(),
                message: e.to_string(),
            })?;
        let uuid = user_data.uuid;

        // Step C — Determine repos to query
        let repos: Vec<(String, String)> = if !self.config.watch_repos.is_empty() {
            // Fast path: watch_repos explicitly configured as "workspace/slug"
            self.config
                .watch_repos
                .iter()
                .filter_map(|entry| {
                    let mut parts = entry.splitn(2, '/');
                    let ws = parts.next()?.to_string();
                    let slug = parts.next()?.to_string();
                    Some((ws, slug))
                })
                .collect()
        } else if let Some(ref workspace) = self.config.workspace {
            // Enumerate repos in the configured workspace
            self.enumerate_workspace_repos(&client, &base, username, token, workspace)
                .await?
        } else {
            return Err(ProviderError::AuthMissing {
                provider: "bitbucket".to_string(),
                reason: "Bitbucket Cloud requires either [bitbucket] watch_repos entries \
                         (format: 'workspace/repo-slug') or [bitbucket] workspace = 'your-workspace' \
                         in config.toml to enumerate repositories."
                    .to_string(),
            });
        };

        // Step D — Fan-out per repo concurrently
        let futures: Vec<_> = repos
            .into_iter()
            .map(|(ws, slug)| {
                let client = client.clone();
                let base = base.clone();
                let uuid = uuid.clone();
                let username = username.clone();
                let token = token.to_string();
                async move {
                    fetch_cloud_repo_prs(&client, &base, &username, &token, &ws, &slug, &uuid)
                        .await
                }
            })
            .collect();

        let results = futures::future::join_all(futures).await;

        let mut all_prs: Vec<PullRequest> = Vec::new();
        let mut first_error: Option<ProviderError> = None;
        let mut error_count = 0usize;
        let total_repos = results.len();
        for result in results {
            match result {
                Ok(prs) => all_prs.extend(prs),
                Err(e) => {
                    tracing::warn!("Bitbucket Cloud per-repo fetch error: {}", e);
                    if first_error.is_none() {
                        first_error = Some(e);
                    }
                    error_count = error_count.saturating_add(1);
                }
            }
        }

        // If every repo failed, surface the error so the user gets a visible signal
        // rather than a silently empty queue.
        if error_count > 0 && error_count == total_repos {
            return Err(first_error.expect("error_count > 0 implies first_error is Some"));
        }

        // Step E — Deduplicate by (repo_full_name, number)
        let mut seen = std::collections::HashSet::new();
        all_prs.retain(|pr| seen.insert((pr.repo_full_name.clone(), pr.number)));

        Ok(all_prs)
    }

    /// Enumerate repository slugs in a workspace.
    async fn enumerate_workspace_repos(
        &self,
        client: &Client,
        base: &str,
        username: &str,
        token: &str,
        workspace: &str,
    ) -> Result<Vec<(String, String)>, ProviderError> {
        let mut repos = Vec::new();
        let mut url = Some(format!(
            "{}/2.0/repositories/{}?role=contributor&pagelen=100",
            base, workspace
        ));

        while let Some(current_url) = url {
            let resp = client
                .get(&current_url)
                .basic_auth(username, Some(token))
                .send()
                .await
                .map_err(|e| ProviderError::ApiError {
                    provider: "bitbucket".to_string(),
                    status: 0,
                    message: e.to_string(),
                })?;

            if !resp.status().is_success() {
                let status = resp.status().as_u16();
                let message = resp.text().await.unwrap_or_default();
                return Err(ProviderError::ApiError {
                    provider: "bitbucket".to_string(),
                    status,
                    message,
                });
            }

            #[derive(serde::Deserialize)]
            struct RepoPage {
                values: Vec<RepoEntry>,
                next: Option<String>,
            }
            #[derive(serde::Deserialize)]
            struct RepoEntry {
                slug: String,
            }

            let page: RepoPage = resp.json().await.map_err(|e| ProviderError::ParseError {
                provider: "bitbucket".to_string(),
                message: e.to_string(),
            })?;

            for repo in page.values {
                repos.push((workspace.to_string(), repo.slug));
            }
            url = page.next.filter(|next| Self::same_origin(base, next));
        }

        Ok(repos)
    }
}

/// Fetch PRs for a single Cloud repository where the user (identified by uuid) is a reviewer.
async fn fetch_cloud_repo_prs(
    client: &Client,
    base: &str,
    username: &str,
    token: &str,
    workspace: &str,
    slug: &str,
    uuid: &str,
) -> Result<Vec<PullRequest>, ProviderError> {
    let mut prs = Vec::new();
    // URL-encode the q-filter; reqwest will not double-encode when using .query()
    // but we build it inline as a string to control encoding precisely
    let q = format!(r#"state="OPEN" AND reviewers.uuid="{}""#, uuid);
    let initial_url = format!(
        "{}/2.0/repositories/{}/{}/pullrequests",
        base, workspace, slug
    );

    let mut current_url = initial_url;
    let mut first = true;

    loop {
        let req = if first {
            first = false;
            client
                .get(&current_url)
                .basic_auth(username, Some(token))
                .query(&[("q", q.as_str()), ("pagelen", "50")])
        } else {
            client
                .get(&current_url)
                .basic_auth(username, Some(token))
        };

        let resp = req
            .send()
            .await
            .map_err(|e| ProviderError::ApiError {
                provider: "bitbucket".to_string(),
                status: 0,
                message: e.to_string(),
            })?;

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let message = resp.text().await.unwrap_or_default();
            return Err(ProviderError::ApiError {
                provider: "bitbucket".to_string(),
                status,
                message,
            });
        }

        let page: CloudPrPage = resp.json().await.map_err(|e| ProviderError::ParseError {
            provider: "bitbucket".to_string(),
            message: e.to_string(),
        })?;

        for cloud_pr in page.values {
            prs.push(normalize_cloud_pr(cloud_pr));
        }

        match page.next {
            Some(url) if BitbucketProvider::same_origin(base, &url) => current_url = url,
            Some(_) => break, // SSRF guard: cursor diverged from configured origin
            None => break,
        }
    }

    Ok(prs)
}

/// Normalize a Data Center PR response to the shared PullRequest model.
fn normalize_dc_pr(pr: DataCenterPr, provider_name: &str) -> PullRequest {
    let url = pr
        .links
        .self_links
        .first()
        .map(|h| h.href.clone())
        .unwrap_or_default();

    let reviewers: Vec<Reviewer> = pr
        .reviewers
        .into_iter()
        .map(|r| Reviewer {
            user: User {
                login: r.user.slug.clone(),
                display_name: Some(r.user.display_name.clone()),
                avatar_url: None,
            },
            state: map_reviewer_state(r.approved, &r.status),
        })
        .collect();

    PullRequest {
        id: PrIdentifier {
            provider: provider_name.to_string(),
            owner: pr.to_ref.repository.project.key.clone(),
            repo: pr.to_ref.repository.slug.clone(),
            number: pr.id,
        },
        number: pr.id,
        title: pr.title,
        url,
        author: User {
            login: pr.author.user.slug,
            display_name: Some(pr.author.user.display_name),
            avatar_url: None,
        },
        reviewers,
        repo_full_name: format!(
            "{}/{}",
            pr.to_ref.repository.project.key, pr.to_ref.repository.slug
        ),
        provider: provider_name.to_string(),
        head_branch: pr.from_ref.display_id,
        base_branch: pr.to_ref.display_id,
        state: PrState::Open,
        review_status: ReviewStatus::NeedsReview,
        ci_status: None,
        draft: false, // Data Center has no draft concept
        created_at: pr.created_date,
        updated_at: pr.updated_date,
        labels: vec![],
        comment_count: pr
            .properties
            .and_then(|p| p.comment_count)
            .unwrap_or(0),
        additions: None,
        deletions: None,
    }
}

/// Normalize a Bitbucket Cloud PR response to the shared PullRequest model.
fn normalize_cloud_pr(pr: CloudPr) -> PullRequest {
    // Build reviewer list, merging reviewers[] with participants[] for state
    let reviewers: Vec<Reviewer> = pr
        .reviewers
        .iter()
        .map(|r| {
            // Find matching participant by account_id to get approved/state
            let participant = pr
                .participants
                .iter()
                .find(|p| p.role == "REVIEWER" && p.user.account_id.as_deref() == Some(&r.account_id));

            let (approved, status) = match participant {
                Some(p) => (p.approved, p.state.as_deref().unwrap_or("")),
                None => (r.approved.unwrap_or(false), ""),
            };

            Reviewer {
                user: User {
                    login: r.account_id.clone(),
                    display_name: Some(r.display_name.clone()),
                    avatar_url: None,
                },
                state: map_reviewer_state(approved, status),
            }
        })
        .collect();

    PullRequest {
        id: PrIdentifier {
            provider: "bitbucket".to_string(),
            owner: pr.destination.repository.workspace.slug.clone(),
            repo: pr.destination.repository.slug.clone(),
            number: pr.id,
        },
        number: pr.id,
        title: pr.title,
        url: pr.links.html.href,
        author: User {
            login: pr
                .author
                .nickname
                .clone()
                .or(pr.author.account_id.clone())
                .unwrap_or_default(),
            display_name: Some(pr.author.display_name),
            avatar_url: None,
        },
        reviewers,
        repo_full_name: pr.destination.repository.full_name,
        provider: "bitbucket".to_string(),
        head_branch: pr.source.branch.name,
        base_branch: pr.destination.branch.name,
        state: PrState::Open,
        review_status: ReviewStatus::NeedsReview,
        ci_status: None,
        draft: pr.draft.unwrap_or(false),
        created_at: pr.created_on,
        updated_at: pr.updated_on,
        labels: vec![],
        comment_count: pr.comment_count.unwrap_or(0),
        additions: None,
        deletions: None,
    }
}

// ── Provider trait implementation ─────────────────────────────────────────────

#[async_trait]
impl Provider for BitbucketProvider {
    fn name(&self) -> &'static str {
        "bitbucket"
    }

    fn display_name(&self) -> &'static str {
        "Bitbucket"
    }

    /// Check Bitbucket auth by resolving BB_TOKEN env var or config.token field.
    ///
    /// SECURITY: Token value is NEVER logged — only success/failure status is logged.
    async fn check_auth(&self) -> AuthStatus {
        match Self::resolve_token(&self.config) {
            Some(_) => {
                tracing::debug!("Bitbucket check_auth: available");
                AuthStatus::Available
            }
            None => {
                let reason = concat!(
                    "Set BB_TOKEN env var or [bitbucket] token = \"...\" in config.toml. ",
                    "For Bitbucket Cloud (Basic auth), also set [bitbucket] username = \"your@atlassian.email\". ",
                    "For Data Center (Bearer auth), only BB_TOKEN or config token is required."
                )
                .to_string();
                tracing::debug!("Bitbucket check_auth: missing");
                AuthStatus::Missing { reason }
            }
        }
    }

    /// Fetch PRs awaiting review from Bitbucket.
    ///
    /// Flow:
    /// 1. Check cache (60s TTL) — return cached data if fresh
    /// 2. Resolve token — return AuthMissing if absent
    /// 3. Dispatch to Cloud or Data Center fetch
    /// 4. Write results to cache atomically (ARCH-04)
    /// 5. Return results
    async fn list_prs(&self) -> Result<Vec<PullRequest>, ProviderError> {
        let cache_path = self.effective_cache_path()?;

        // 1. Cache check — return early on cache hit
        if let Some(entry) = cache::read_cache::<Vec<PullRequest>>(&cache_path) {
            if entry.is_fresh() {
                tracing::debug!("Bitbucket cache hit — returning cached PRs");
                return Ok(entry.data);
            }
            tracing::debug!("Bitbucket cache miss or expired — fetching from API");
        }

        // 2. Token resolution — SECURITY: never log this value
        let token = Self::resolve_token(&self.config).ok_or_else(|| ProviderError::AuthMissing {
            provider: "bitbucket".to_string(),
            reason: "Set BB_TOKEN or [bitbucket] token = \"...\" in config.toml".to_string(),
        })?;

        // 3. Dispatch to Cloud or Data Center path based on detected mode
        let prs = match self.mode {
            BitbucketMode::Cloud => self.fetch_cloud(&token).await?,
            BitbucketMode::DataCenter => self.fetch_data_center(&token).await?,
        };

        // 4. Write to cache atomically — log debug if write fails, do NOT error the caller
        if let Err(e) = cache::write_cache(&cache_path, &prs, 60) {
            tracing::debug!(
                "Failed to write Bitbucket cache to {:?}: {}",
                cache_path,
                e
            );
        }

        Ok(prs)
    }

    async fn get_pr_details(&self, _pr_id: &PrIdentifier) -> Result<PullRequest, ProviderError> {
        Err(ProviderError::NotImplemented {
            provider: "bitbucket".to_string(),
        })
    }

    async fn get_pr_diff(&self, _pr_id: &PrIdentifier) -> Result<String, ProviderError> {
        Err(ProviderError::NotImplemented {
            provider: "bitbucket".to_string(),
        })
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

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

    // Serialise all tests that mutate BB_TOKEN so they cannot race each other.
    // cargo test runs tests within a binary on multiple OS threads by default;
    // env-var mutations are process-wide and unsound without serialisation.
    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

    // ── Constructor / trait method smoke tests ────────────────────────────────

    #[test]
    fn provider_name() {
        let provider = BitbucketProvider::new(BitbucketConfig::default());
        assert_eq!(provider.name(), "bitbucket");
        assert_eq!(provider.display_name(), "Bitbucket");
    }

    #[test]
    fn provider_name_test_constructor() {
        let provider = BitbucketProvider::new_with_base_url(
            BitbucketConfig::default(),
            "http://localhost:0".to_string(),
            std::path::PathBuf::from("/tmp/prlens-test-bitbucket-cache.json"),
        );
        assert_eq!(provider.name(), "bitbucket");
        assert_eq!(provider.display_name(), "Bitbucket");
    }

    // ── Mode detection tests ─────────────────────────────────────────────────

    #[test]
    fn mode_detection_cloud() {
        let mode = BitbucketMode::from_base_url("https://api.bitbucket.org/2.0");
        assert!(matches!(mode, BitbucketMode::Cloud));
    }

    #[test]
    fn mode_detection_data_center() {
        let mode =
            BitbucketMode::from_base_url("https://bitbucket.mycompany.com/rest/api/1.0");
        assert!(matches!(mode, BitbucketMode::DataCenter));
    }

    #[test]
    fn mode_detection_default_is_cloud() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: ENV_MUTEX serialises all BB_SERVER_URL mutations in this test binary.
        unsafe { std::env::remove_var("BB_SERVER_URL"); }
        // When no base_url is configured and no env var set, new() defaults to Cloud
        let provider = BitbucketProvider::new(BitbucketConfig::default());
        assert!(matches!(provider.mode, BitbucketMode::Cloud));
    }

    #[test]
    fn mode_detection_custom_url_is_data_center() {
        let config = BitbucketConfig {
            base_url: Some("https://bb.internal.example.com/rest/api/1.0".to_string()),
            ..BitbucketConfig::default()
        };
        let provider = BitbucketProvider::new(config);
        assert!(matches!(provider.mode, BitbucketMode::DataCenter));
    }

    // ── Token resolution tests ───────────────────────────────────────────────

    #[test]
    fn resolve_token_bb_token_env_var() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: ENV_MUTEX serialises all BB_TOKEN mutations in this test binary.
        unsafe {
            std::env::set_var("BB_TOKEN", "envtoken");
        }
        let config = BitbucketConfig::default();
        let result = BitbucketProvider::resolve_token(&config);
        unsafe {
            std::env::remove_var("BB_TOKEN");
        }
        assert_eq!(result, Some("envtoken".to_string()));
    }

    #[test]
    fn resolve_token_config_fallback_when_env_absent() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: ENV_MUTEX serialises all BB_TOKEN mutations in this test binary.
        unsafe {
            std::env::remove_var("BB_TOKEN");
        }
        let config = BitbucketConfig {
            token: Some("conftoken".to_string()),
            ..BitbucketConfig::default()
        };
        let result = BitbucketProvider::resolve_token(&config);
        assert_eq!(result, Some("conftoken".to_string()));
    }

    #[test]
    fn resolve_token_none_when_both_absent() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: ENV_MUTEX serialises all BB_TOKEN mutations in this test binary.
        unsafe {
            std::env::remove_var("BB_TOKEN");
        }
        let config = BitbucketConfig::default(); // token == None
        let result = BitbucketProvider::resolve_token(&config);
        assert_eq!(result, None);
    }

    #[test]
    fn resolve_token_env_var_takes_priority_over_config() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: ENV_MUTEX serialises all BB_TOKEN mutations in this test binary.
        unsafe {
            std::env::set_var("BB_TOKEN", "envwins");
        }
        let config = BitbucketConfig {
            token: Some("configtoken".to_string()),
            ..BitbucketConfig::default()
        };
        let result = BitbucketProvider::resolve_token(&config);
        unsafe {
            std::env::remove_var("BB_TOKEN");
        }
        assert_eq!(result, Some("envwins".to_string()));
    }

    #[test]
    fn resolve_token_empty_env_var_falls_back_to_config() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: ENV_MUTEX serialises all BB_TOKEN mutations in this test binary.
        unsafe {
            std::env::set_var("BB_TOKEN", "");
        }
        let config = BitbucketConfig {
            token: Some("configtoken".to_string()),
            ..BitbucketConfig::default()
        };
        let result = BitbucketProvider::resolve_token(&config);
        unsafe {
            std::env::remove_var("BB_TOKEN");
        }
        assert_eq!(result, Some("configtoken".to_string()));
    }

    // ── check_auth tests (async) ─────────────────────────────────────────────

    #[tokio::test]
    async fn check_auth_missing_when_no_token() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        let provider = BitbucketProvider::new_with_base_url(
            BitbucketConfig::default(), // token == None
            "http://localhost:0".to_string(),
            std::path::PathBuf::from("/tmp/prlens-test-bitbucket-check-auth.json"),
        );
        let saved = std::env::var("BB_TOKEN").ok();
        // SAFETY: ENV_MUTEX serialises all BB_TOKEN mutations in this test binary.
        unsafe {
            std::env::remove_var("BB_TOKEN");
        }
        let status = provider.check_auth().await;
        if let Some(val) = saved {
            unsafe {
                std::env::set_var("BB_TOKEN", val);
            }
        }
        match status {
            AuthStatus::Missing { reason } => {
                assert!(
                    reason.contains("BB_TOKEN"),
                    "Missing reason should mention BB_TOKEN, got: {}",
                    reason
                );
                assert!(
                    reason.contains("[bitbucket] token"),
                    "Missing reason should mention [bitbucket] token, got: {}",
                    reason
                );
            }
            AuthStatus::Available => panic!("Expected Missing, got Available"),
        }
    }

    #[tokio::test]
    async fn check_auth_available_when_bb_token_set() {
        let config = BitbucketConfig {
            token: Some("testtoken123".to_string()),
            ..BitbucketConfig::default()
        };
        let provider = BitbucketProvider::new(config);
        let status = provider.check_auth().await;
        assert_eq!(status, AuthStatus::Available);
    }

    #[tokio::test]
    async fn check_auth_available_when_config_token_set() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: ENV_MUTEX serialises all BB_TOKEN mutations in this test binary.
        unsafe {
            std::env::remove_var("BB_TOKEN");
        }
        let config = BitbucketConfig {
            token: Some("myconfig_token".to_string()),
            ..BitbucketConfig::default()
        };
        let provider = BitbucketProvider::new(config);
        let status = provider.check_auth().await;
        assert_eq!(status, AuthStatus::Available);
    }

    // ── Normalization unit tests ─────────────────────────────────────────────

    #[test]
    fn normalize_dc_pr_epoch_ms_timestamp() {
        // epoch ms 1731663000000 → 2024-11-15T09:30:00Z
        let dc_pr = DataCenterPr {
            id: 1,
            title: "Test PR".to_string(),
            links: DcLinks {
                self_links: vec![DcHref {
                    href: "https://bb.example.com/pr/1".to_string(),
                }],
            },
            author: DcParticipant {
                user: DcUser {
                    slug: "alice".to_string(),
                    display_name: "Alice Smith".to_string(),
                },
            },
            from_ref: DcRef {
                display_id: "feature/test".to_string(),
                repository: DcRepository {
                    slug: "myrepo".to_string(),
                    project: DcProject {
                        key: "PROJ".to_string(),
                    },
                },
            },
            to_ref: DcRef {
                display_id: "main".to_string(),
                repository: DcRepository {
                    slug: "myrepo".to_string(),
                    project: DcProject {
                        key: "PROJ".to_string(),
                    },
                },
            },
            reviewers: vec![],
            created_date: DateTime::from_timestamp(1731663000000 / 1000, 0).unwrap(),
            updated_date: DateTime::from_timestamp(1731663000000 / 1000, 0).unwrap(),
            properties: None,
        };

        let pr = normalize_dc_pr(dc_pr, "bitbucket");
        // 1731663000 seconds = 2024-11-15T09:30:00Z
        assert_eq!(pr.created_at.to_rfc3339(), "2024-11-15T09:30:00+00:00");
        assert!(!pr.draft, "Data Center PRs should never be draft");
        assert_eq!(pr.provider, "bitbucket");
    }

    #[test]
    fn map_reviewer_state_approved() {
        assert!(matches!(
            map_reviewer_state(true, "APPROVED"),
            ReviewerState::Approved
        ));
    }

    #[test]
    fn map_reviewer_state_needs_work() {
        assert!(matches!(
            map_reviewer_state(false, "NEEDS_WORK"),
            ReviewerState::ChangesRequested
        ));
        assert!(matches!(
            map_reviewer_state(false, "needs_work"),
            ReviewerState::ChangesRequested
        ));
    }

    #[test]
    fn map_reviewer_state_pending() {
        assert!(matches!(
            map_reviewer_state(false, "UNAPPROVED"),
            ReviewerState::Pending
        ));
    }

    // ── SSRF mitigation tests ────────────────────────────────────────────────

    #[test]
    fn validate_base_url_rejects_http_non_localhost() {
        let result = BitbucketProvider::validate_base_url_https("http://evil.com/api");
        assert!(result.is_err());
        if let Err(ProviderError::ApiError { message, .. }) = result {
            assert!(message.contains("must use HTTPS"));
        }
    }

    #[test]
    fn validate_base_url_allows_https() {
        assert!(
            BitbucketProvider::validate_base_url_https("https://api.bitbucket.org").is_ok()
        );
    }

    #[test]
    fn validate_base_url_allows_http_localhost() {
        assert!(
            BitbucketProvider::validate_base_url_https("http://localhost:9090").is_ok()
        );
        assert!(
            BitbucketProvider::validate_base_url_https("http://127.0.0.1:9090").is_ok()
        );
    }
}