github-bot-sdk 0.2.1

A comprehensive Rust SDK for GitHub App integration with authentication, webhooks, and API client
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
// Spec: docs/specs/interfaces/pull-request-operations.md
// Pull request, review, comment, and label operations.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::client::issue::{Comment, IssueUser, Label, LabelsRequest, Milestone};
use crate::client::{parse_link_header, InstallationClient, PagedResponse};
use crate::error::ApiError;

/// GitHub pull request.
///
/// Represents a pull request with all its metadata.
///
/// See docs/spec/interfaces/pull-request-operations.md
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequest {
    /// Unique pull request identifier
    pub id: u64,

    /// Node ID for GraphQL API
    pub node_id: String,

    /// Pull request number (repository-specific)
    pub number: u64,

    /// Pull request title
    pub title: String,

    /// Pull request body content (Markdown)
    pub body: Option<String>,

    /// Pull request state
    pub state: String, // "open", "closed"

    /// User who created the pull request
    pub user: IssueUser,

    /// Head branch information
    pub head: PullRequestBranch,

    /// Base branch information
    pub base: PullRequestBranch,

    /// Whether the pull request is a draft
    pub draft: bool,

    /// Whether the pull request is merged
    pub merged: bool,

    /// Whether the pull request is mergeable
    pub mergeable: Option<bool>,

    /// Merge commit SHA (if merged)
    pub merge_commit_sha: Option<String>,

    /// Assigned users
    pub assignees: Vec<IssueUser>,

    /// Requested reviewers
    pub requested_reviewers: Vec<IssueUser>,

    /// Applied labels
    pub labels: Vec<Label>,

    /// Milestone
    pub milestone: Option<Milestone>,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Last update timestamp
    pub updated_at: DateTime<Utc>,

    /// Close timestamp
    pub closed_at: Option<DateTime<Utc>>,

    /// Merge timestamp
    pub merged_at: Option<DateTime<Utc>>,

    /// Pull request URL
    pub html_url: String,
}

/// Branch information in a pull request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequestBranch {
    /// Branch name
    #[serde(rename = "ref")]
    pub branch_ref: String,

    /// Commit SHA
    pub sha: String,

    /// Repository information
    pub repo: PullRequestRepo,
}

/// Repository information in a pull request branch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequestRepo {
    /// Repository ID
    pub id: u64,

    /// Repository name
    pub name: String,

    /// Full repository name (owner/repo)
    pub full_name: String,
}

/// Pull request review.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Review {
    /// Unique review identifier
    pub id: u64,

    /// Node ID for GraphQL API
    pub node_id: String,

    /// User who submitted the review
    pub user: IssueUser,

    /// Review body content (Markdown)
    pub body: Option<String>,

    /// Review state
    pub state: String, // "APPROVED", "CHANGES_REQUESTED", "COMMENTED", "DISMISSED", "PENDING"

    /// Commit SHA that was reviewed
    pub commit_id: String,

    /// Creation timestamp
    pub submitted_at: Option<DateTime<Utc>>,

    /// Review URL
    pub html_url: String,
}

/// Comment on a pull request (review comment on code).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequestComment {
    /// Unique comment identifier
    pub id: u64,

    /// Node ID for GraphQL API
    pub node_id: String,

    /// Comment body content (Markdown)
    pub body: String,

    /// User who created the comment
    pub user: IssueUser,

    /// File path
    pub path: String,

    /// Line number (if single-line comment)
    pub line: Option<u64>,

    /// Commit SHA
    pub commit_id: String,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Last update timestamp
    pub updated_at: DateTime<Utc>,

    /// Comment URL
    pub html_url: String,
}

/// Request to create a new pull request.
#[derive(Debug, Clone, Serialize)]
pub struct CreatePullRequestRequest {
    /// Pull request title (required)
    pub title: String,

    /// Head branch (required) - format: "username:branch" for forks
    pub head: String,

    /// Base branch (required)
    pub base: String,

    /// Pull request body content (Markdown)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,

    /// Whether to create as draft
    #[serde(skip_serializing_if = "Option::is_none")]
    pub draft: Option<bool>,

    /// Milestone number
    #[serde(skip_serializing_if = "Option::is_none")]
    pub milestone: Option<u64>,

    /// Whether maintainers of the base repository can push to the head branch.
    ///
    /// When `true`, maintainers of the base repository (contributors with push
    /// access) can push commits to the head branch of this pull request, even
    /// when the head branch lives in a fork. Defaults to `true` on the GitHub
    /// API for fork-sourced pull requests when not provided.
    ///
    /// # Example
    ///
    /// ```
    /// use github_bot_sdk::client::CreatePullRequestRequest;
    ///
    /// let request = CreatePullRequestRequest {
    ///     title: "My feature".to_string(),
    ///     head: "contributor:feature-branch".to_string(),
    ///     base: "main".to_string(),
    ///     body: None,
    ///     draft: None,
    ///     milestone: None,
    ///     maintainer_can_modify: Some(true),
    /// };
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maintainer_can_modify: Option<bool>,
}

/// Request to update an existing pull request.
///
/// Note: milestone assignment is not supported here — the GitHub Pulls API
/// silently ignores the `milestone` field. Use `PullRequestsClient::set_milestone`
/// which delegates to the Issues API endpoint that actually applies the milestone.
#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdatePullRequestRequest {
    /// Pull request title
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Pull request body content (Markdown)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,

    /// Pull request state
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>, // "open" or "closed"

    /// Base branch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base: Option<String>,
}

/// Request to merge a pull request.
#[derive(Debug, Clone, Serialize, Default)]
pub struct MergePullRequestRequest {
    /// Merge commit message title
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_title: Option<String>,

    /// Merge commit message body
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_message: Option<String>,

    /// SHA that pull request head must match
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sha: Option<String>,

    /// Merge method
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merge_method: Option<String>, // "merge", "squash", "rebase"
}

/// Result of merging a pull request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeResult {
    /// Whether the merge was successful
    pub merged: bool,

    /// Merge commit SHA
    pub sha: String,

    /// Message describing the result
    pub message: String,
}

/// Request to create a review.
#[derive(Debug, Clone, Serialize)]
pub struct CreateReviewRequest {
    /// Commit SHA to review (optional, defaults to PR head)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_id: Option<String>,

    /// Review body content (Markdown)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,

    /// Review event
    pub event: String, // "APPROVE", "REQUEST_CHANGES", "COMMENT"
}

/// Request to update a review.
#[derive(Debug, Clone, Serialize)]
pub struct UpdateReviewRequest {
    /// Review body content (Markdown, required)
    pub body: String,
}

/// Request to dismiss a review.
#[derive(Debug, Clone, Serialize)]
pub struct DismissReviewRequest {
    /// Dismissal message (required)
    pub message: String,
}

/// Request to create a pull request comment.
#[derive(Debug, Clone, Serialize)]
pub struct CreatePullRequestCommentRequest {
    /// Comment body content (Markdown, required)
    pub body: String,
}

/// Request to update a pull request comment.
#[derive(Debug, Clone, Serialize)]
pub struct UpdatePullRequestCommentRequest {
    /// Comment body content (Markdown, required)
    pub body: String,
}

// ============================================================================
// PullRequestsClient
// ============================================================================

/// Domain client for pull request operations.
///
/// Obtained via [`InstallationClient::pull_requests()`]. Cheap to clone (Arc-backed).
///
/// See docs/specs/interfaces/pull-request-operations.md
#[derive(Debug, Clone)]
pub struct PullRequestsClient {
    client: InstallationClient,
}

impl PullRequestsClient {
    pub(crate) fn new(client: InstallationClient) -> Self {
        Self { client }
    }

    // --- Pull Request CRUD ---

    /// List pull requests in a repository.
    ///
    /// Returns a paginated response with pull requests and pagination metadata.
    /// Use the pagination information to fetch subsequent pages if needed.
    ///
    /// # Arguments
    ///
    /// * `owner` - Repository owner
    /// * `repo` - Repository name
    /// * `state` - Filter by state (`"open"`, `"closed"`, or `"all"`)
    /// * `page` - Page number (1-indexed, omit for first page)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use github_bot_sdk::client::PullRequestsClient;
    /// # async fn example(client: &PullRequestsClient) -> Result<(), Box<dyn std::error::Error>> {
    /// // Get first page
    /// let response = client.list("owner", "repo", None, None).await?;
    /// println!("Got {} pull requests", response.items.len());
    ///
    /// // Check if more pages exist
    /// if response.has_next() {
    ///     if let Some(next_page) = response.next_page_number() {
    ///         let next_response = client.list("owner", "repo", None, Some(next_page)).await?;
    ///         println!("Got {} more PRs", next_response.items.len());
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn list(
        &self,
        owner: &str,
        repo: &str,
        state: Option<&str>,
        page: Option<u32>,
    ) -> Result<PagedResponse<PullRequest>, ApiError> {
        let mut path = format!("/repos/{}/{}/pulls", owner, repo);
        let mut query_params = Vec::new();

        if let Some(state_value) = state {
            query_params.push(format!("state={}", state_value));
        }
        if let Some(page_num) = page {
            query_params.push(format!("page={}", page_num));
        }

        if !query_params.is_empty() {
            path = format!("{}?{}", path, query_params.join("&"));
        }

        let response = self.client.get(&path).await?;
        let status = response.status();

        if !status.is_success() {
            return Err(match status.as_u16() {
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }

        // Parse Link header for pagination
        let pagination = response
            .headers()
            .get("Link")
            .and_then(|h| h.to_str().ok())
            .map(|h| parse_link_header(Some(h)))
            .unwrap_or_default();

        // Parse response body
        let items: Vec<PullRequest> = response.json().await.map_err(ApiError::from)?;

        Ok(PagedResponse {
            items,
            total_count: None, // GitHub doesn't provide total count in list responses
            pagination,
        })
    }

    /// Get a specific pull request by number.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn get(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<PullRequest, ApiError> {
        let path = format!("/repos/{}/{}/pulls/{}", owner, repo, pull_number);
        let response = self.client.get(&path).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Create a new pull request.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn create(
        &self,
        owner: &str,
        repo: &str,
        request: CreatePullRequestRequest,
    ) -> Result<PullRequest, ApiError> {
        let path = format!("/repos/{}/{}/pulls", owner, repo);
        let response = self.client.post(&path, &request).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                422 => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Validation failed".to_string());
                    ApiError::InvalidRequest { message }
                }
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Update an existing pull request.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn update(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        request: UpdatePullRequestRequest,
    ) -> Result<PullRequest, ApiError> {
        let path = format!("/repos/{}/{}/pulls/{}", owner, repo, pull_number);
        let response = self.client.patch(&path, &request).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                422 => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Validation failed".to_string());
                    ApiError::InvalidRequest { message }
                }
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Merge a pull request.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn merge(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        request: MergePullRequestRequest,
    ) -> Result<MergeResult, ApiError> {
        let path = format!("/repos/{}/{}/pulls/{}/merge", owner, repo, pull_number);
        let response = self.client.put(&path, &request).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                405 => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Pull request not mergeable".to_string());
                    ApiError::HttpError {
                        status: 405,
                        message,
                    }
                }
                409 => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Merge conflict".to_string());
                    ApiError::HttpError {
                        status: 409,
                        message,
                    }
                }
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Set the milestone on a pull request.
    ///
    /// The GitHub Pulls API silently ignores the milestone field, so this method
    /// delegates to the Issues API (PATCH /repos/{owner}/{repo}/issues/{number})
    /// which correctly applies the milestone, then re-fetches the PR to return
    /// the updated state.
    ///
    /// # Partial-failure note
    ///
    /// If the Issues API call succeeds but the subsequent `get()` call fails
    /// (e.g. due to a transient network error), this method returns an error even
    /// though the milestone **was** actually set on the PR. Callers should treat
    /// an error response as "milestone state unknown" rather than "milestone not
    /// set" and may wish to re-fetch the PR to confirm the current state.
    ///
    /// See docs/specs/interfaces/pull-request-operations.md
    pub async fn set_milestone(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        milestone_number: Option<u64>,
    ) -> Result<PullRequest, ApiError> {
        self.client
            .issues()
            .set_milestone(owner, repo, pull_number, milestone_number)
            .await?;
        self.get(owner, repo, pull_number).await
    }

    // ========================================================================
    // Pull Request Review Operations
    // ========================================================================

    /// List reviews on a pull request.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn list_reviews(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<Vec<Review>, ApiError> {
        let path = format!("/repos/{}/{}/pulls/{}/reviews", owner, repo, pull_number);
        let response = self.client.get(&path).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Get a specific review by ID.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn get_review(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        review_id: u64,
    ) -> Result<Review, ApiError> {
        let path = format!(
            "/repos/{}/{}/pulls/{}/reviews/{}",
            owner, repo, pull_number, review_id
        );
        let response = self.client.get(&path).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Create a review on a pull request.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn create_review(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        request: CreateReviewRequest,
    ) -> Result<Review, ApiError> {
        let path = format!("/repos/{}/{}/pulls/{}/reviews", owner, repo, pull_number);
        let response = self.client.post(&path, &request).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                422 => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Validation failed".to_string());
                    ApiError::InvalidRequest { message }
                }
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Update a pending review.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn update_review(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        review_id: u64,
        request: UpdateReviewRequest,
    ) -> Result<Review, ApiError> {
        let path = format!(
            "/repos/{}/{}/pulls/{}/reviews/{}",
            owner, repo, pull_number, review_id
        );
        let response = self.client.put(&path, &request).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                422 => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Validation failed".to_string());
                    ApiError::InvalidRequest { message }
                }
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Dismiss a review.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    pub async fn dismiss_review(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        review_id: u64,
        request: DismissReviewRequest,
    ) -> Result<Review, ApiError> {
        let path = format!(
            "/repos/{}/{}/pulls/{}/reviews/{}/dismissals",
            owner, repo, pull_number, review_id
        );
        let response = self.client.put(&path, &request).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(match status.as_u16() {
                422 => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Validation failed".to_string());
                    ApiError::InvalidRequest { message }
                }
                404 => ApiError::NotFound,
                403 => ApiError::AuthorizationFailed,
                401 => ApiError::AuthenticationFailed,
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    ApiError::HttpError {
                        status: status.as_u16(),
                        message,
                    }
                }
            });
        }
        response.json().await.map_err(ApiError::from)
    }

    // ========================================================================
    // Pull Request Comment Operations
    // ========================================================================

    /// List all conversation-thread comments on a pull request (auto-paginated).
    ///
    /// Uses the Issues comments endpoint per GitHub API design.
    ///
    /// See docs/specs/interfaces/pull-request-operations.md
    pub async fn list_comments(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
    ) -> Result<Vec<Comment>, ApiError> {
        let first_page = format!(
            "/repos/{}/{}/issues/{}/comments?per_page=100",
            owner, repo, pull_number
        );
        self.client.fetch_all_pages(&first_page).await
    }

    /// Add a conversation-thread comment to a pull request.
    ///
    /// Uses the Issues comments endpoint per GitHub API design.
    ///
    /// See docs/specs/interfaces/pull-request-operations.md
    pub async fn create_comment(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        request: CreatePullRequestCommentRequest,
    ) -> Result<Comment, ApiError> {
        let path = format!("/repos/{}/{}/issues/{}/comments", owner, repo, pull_number);
        let response = self.client.post(&path, &request).await?;
        let status = response.status();
        if !status.is_success() {
            return Err(super::map_http_error(status, response).await);
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Update an existing pull request conversation-thread comment.
    ///
    /// See docs/specs/interfaces/pull-request-operations.md
    pub async fn update_comment(
        &self,
        owner: &str,
        repo: &str,
        comment_id: u64,
        request: UpdatePullRequestCommentRequest,
    ) -> Result<Comment, ApiError> {
        let path = format!("/repos/{}/{}/issues/comments/{}", owner, repo, comment_id);
        let response = self.client.patch(&path, &request).await?;
        let status = response.status();
        if !status.is_success() {
            return Err(super::map_http_error(status, response).await);
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Delete a pull request conversation-thread comment.
    ///
    /// See docs/specs/interfaces/pull-request-operations.md
    pub async fn delete_comment(
        &self,
        owner: &str,
        repo: &str,
        comment_id: u64,
    ) -> Result<(), ApiError> {
        let path = format!("/repos/{}/{}/issues/comments/{}", owner, repo, comment_id);
        let response = self.client.delete(&path).await?;
        let status = response.status();
        if !status.is_success() {
            return Err(super::map_http_error(status, response).await);
        }
        Ok(())
    }

    // ========================================================================
    // Pull Request Label Operations
    // ========================================================================

    /// Add labels to a pull request.
    ///
    /// See docs/specs/interfaces/pull-request-operations.md
    pub async fn add_labels(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        labels: Vec<String>,
    ) -> Result<Vec<Label>, ApiError> {
        // PRs use the same label endpoint as issues
        let path = format!("/repos/{}/{}/issues/{}/labels", owner, repo, pull_number);
        let body = LabelsRequest { labels };
        let response = self.client.post(&path, &body).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(super::map_http_error(status, response).await);
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Replace all labels on a pull request.
    ///
    /// Replaces the entire set of labels. Pass an empty vec to clear all labels.
    ///
    /// See docs/specs/interfaces/pull-request-operations.md
    pub async fn replace_labels(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        labels: Vec<String>,
    ) -> Result<Vec<Label>, ApiError> {
        // PRs use the same label endpoint as issues
        let path = format!("/repos/{}/{}/issues/{}/labels", owner, repo, pull_number);
        let body = LabelsRequest { labels };
        let response = self.client.put(&path, &body).await?;
        let status = response.status();
        if !status.is_success() {
            return Err(super::map_http_error(status, response).await);
        }
        response.json().await.map_err(ApiError::from)
    }

    /// Remove a label from a pull request.
    ///
    /// See docs/spec/interfaces/pull-request-operations.md
    ///
    /// # Error mapping
    ///
    /// GitHub returns HTTP 422 when the label name is unprocessable (e.g. does
    /// not exist on the repository).  This method maps that to
    /// [`ApiError::InvalidRequest`], which is the correct semantic mapping and
    /// is consistent with how other label methods in this file behave.  Callers
    /// that previously matched on `ApiError::HttpError { status: 422, .. }`
    /// must be updated to match `ApiError::InvalidRequest { .. }` instead.
    pub async fn remove_label(
        &self,
        owner: &str,
        repo: &str,
        pull_number: u64,
        name: &str,
    ) -> Result<Vec<Label>, ApiError> {
        // PRs use the same label endpoint as issues
        let path = format!(
            "/repos/{}/{}/issues/{}/labels/{}",
            owner,
            repo,
            pull_number,
            urlencoding::encode(name)
        );
        let response = self.client.delete(&path).await?;

        let status = response.status();
        if !status.is_success() {
            return Err(super::map_http_error(status, response).await);
        }
        response.json().await.map_err(ApiError::from)
    }
}

#[cfg(test)]
#[path = "pull_request_tests.rs"]
mod tests;