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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
//! Tests for pull request operations.

use super::*;
use crate::auth::InstallationId;
use crate::client::{ClientConfig, GitHubClient};
use crate::error::ApiError;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[path = "test_helpers.rs"]
mod test_helpers;
use test_helpers::MockAuthProvider;

// ============================================================================
// Type Construction Tests
// ============================================================================

mod construction {
    use super::*;

    /// Verify CreatePullRequestRequest with required fields only.
    ///
    /// Ensures minimal PR creation request can be constructed.
    #[test]
    fn test_create_pull_request_request_minimal() {
        let request = CreatePullRequestRequest {
            title: "Test PR".to_string(),
            head: "feature-branch".to_string(),
            base: "main".to_string(),
            body: None,
            draft: None,
            milestone: None,
            maintainer_can_modify: None,
        };

        assert_eq!(request.title, "Test PR");
        assert_eq!(request.head, "feature-branch");
        assert_eq!(request.base, "main");
        assert!(request.body.is_none());
        assert!(request.draft.is_none());
    }

    /// Verify CreatePullRequestRequest with all fields populated.
    ///
    /// Ensures PR creation request supports all optional fields, including
    /// maintainer_can_modify for fork-sourced pull requests.
    #[test]
    fn test_create_pull_request_request_full() {
        let request = CreatePullRequestRequest {
            title: "Test PR".to_string(),
            head: "contributor:feature-branch".to_string(),
            base: "main".to_string(),
            body: Some("Detailed description".to_string()),
            draft: Some(true),
            milestone: Some(5),
            maintainer_can_modify: Some(true),
        };

        assert_eq!(request.title, "Test PR");
        assert_eq!(request.head, "contributor:feature-branch");
        assert_eq!(request.base, "main");
        assert_eq!(request.body, Some("Detailed description".to_string()));
        assert_eq!(request.draft, Some(true));
        assert_eq!(request.milestone, Some(5));
        assert_eq!(request.maintainer_can_modify, Some(true));
    }

    /// Verify CreatePullRequestRequest serializes maintainer_can_modify as boolean when Some.
    ///
    /// When maintainer_can_modify is Some(true) or Some(false), the field must be
    /// present in JSON with the correct boolean value so GitHub respects the caller's
    /// explicit preference.
    #[test]
    fn test_create_pr_request_with_maintainer_modify() {
        let request_true = CreatePullRequestRequest {
            title: "Test PR".to_string(),
            head: "contributor:feature".to_string(),
            base: "main".to_string(),
            body: None,
            draft: None,
            milestone: None,
            maintainer_can_modify: Some(true),
        };

        let json_true = serde_json::to_value(&request_true).unwrap();
        assert_eq!(json_true["maintainer_can_modify"], true);

        let request_false = CreatePullRequestRequest {
            title: "Test PR".to_string(),
            head: "contributor:feature".to_string(),
            base: "main".to_string(),
            body: None,
            draft: None,
            milestone: None,
            maintainer_can_modify: Some(false),
        };

        let json_false = serde_json::to_value(&request_false).unwrap();
        assert_eq!(json_false["maintainer_can_modify"], false);
    }

    /// Verify CreatePullRequestRequest omits maintainer_can_modify from JSON when None.
    ///
    /// When maintainer_can_modify is None, the field must be absent from serialized
    /// JSON so that the GitHub API applies its own default without explicit override.
    #[test]
    fn test_create_pr_request_without_maintainer_modify() {
        let request = CreatePullRequestRequest {
            title: "Test PR".to_string(),
            head: "feature-branch".to_string(),
            base: "main".to_string(),
            body: None,
            draft: None,
            milestone: None,
            maintainer_can_modify: None,
        };

        let json = serde_json::to_value(&request).unwrap();
        assert!(json.get("maintainer_can_modify").is_none());
    }

    /// Verify UpdatePullRequestRequest with selective updates.
    ///
    /// Ensures PR update request supports partial field updates.
    #[test]
    fn test_update_pull_request_request_partial() {
        let request = UpdatePullRequestRequest {
            title: Some("Updated title".to_string()),
            body: None,
            state: None,
            base: None,
        };

        assert_eq!(request.title, Some("Updated title".to_string()));
        assert!(request.body.is_none());
        assert!(request.state.is_none());
    }

    /// Verify MergePullRequestRequest with merge method.
    ///
    /// Ensures merge request supports different merge strategies.
    #[test]
    fn test_merge_pull_request_request() {
        let request = MergePullRequestRequest {
            commit_title: Some("Merge feature".to_string()),
            commit_message: Some("Closes #123".to_string()),
            sha: None,
            merge_method: Some("squash".to_string()),
        };

        assert_eq!(request.commit_title, Some("Merge feature".to_string()));
        assert_eq!(request.merge_method, Some("squash".to_string()));
    }

    /// Verify CreateReviewRequest with event type.
    ///
    /// Ensures review request supports different review types.
    #[test]
    fn test_create_review_request() {
        let request = CreateReviewRequest {
            commit_id: Some("abc123".to_string()),
            body: Some("Looks good!".to_string()),
            event: "APPROVE".to_string(),
        };

        assert_eq!(request.event, "APPROVE");
        assert_eq!(request.body, Some("Looks good!".to_string()));
    }
}

// ============================================================================
// Pull Request Operations Tests
// ============================================================================

mod pull_request_operations {
    use super::*;

    /// Verify list_pull_requests returns PRs from GitHub API.
    ///
    /// Tests: docs/spec/assertions.md #10
    #[tokio::test]
    async fn test_list_pull_requests() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/repos/owner/repo/pulls"))
            .and(header("Authorization", "Bearer test-token"))
            .and(header("Accept", "application/vnd.github+json"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
                {
                    "id": 1,
                    "node_id": "PR_1",
                    "number": 42,
                    "title": "Test PR",
                    "body": "Description",
                    "state": "open",
                    "user": {
                        "login": "testuser",
                        "id": 123,
                        "node_id": "U_123",
                        "type": "User"
                    },
                    "head": {
                        "ref": "feature-branch",
                        "sha": "abc123",
                        "repo": {
                            "id": 456,
                            "name": "repo",
                            "full_name": "owner/repo"
                        }
                    },
                    "base": {
                        "ref": "main",
                        "sha": "def456",
                        "repo": {
                            "id": 456,
                            "name": "repo",
                            "full_name": "owner/repo"
                        }
                    },
                    "draft": false,
                    "merged": false,
                    "mergeable": true,
                    "merge_commit_sha": null,
                    "assignees": [],
                    "requested_reviewers": [],
                    "labels": [],
                    "milestone": null,
                    "created_at": "2024-01-01T00:00:00Z",
                    "updated_at": "2024-01-01T00:00:00Z",
                    "closed_at": null,
                    "merged_at": null,
                    "html_url": "https://github.com/owner/repo/pull/42"
                }
            ])))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let response = client
            .pull_requests()
            .list("owner", "repo", None, None)
            .await
            .unwrap();

        assert_eq!(response.items.len(), 1);
        assert_eq!(response.items[0].number, 42);
        assert_eq!(response.items[0].title, "Test PR");
        assert_eq!(response.items[0].state, "open");
    }

    /// Verify get_pull_request returns single PR from GitHub API.
    ///
    /// Tests: docs/spec/assertions.md #10
    #[tokio::test]
    async fn test_get_pull_request() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/repos/owner/repo/pulls/42"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": 1,
                "node_id": "PR_1",
                "number": 42,
                "title": "Test PR",
                "body": "Description",
                "state": "open",
                "user": {
                    "login": "testuser",
                    "id": 123,
                    "node_id": "U_123",
                    "type": "User"
                },
                "head": {
                    "ref": "feature-branch",
                    "sha": "abc123",
                    "repo": {
                        "id": 456,
                        "name": "repo",
                        "full_name": "owner/repo"
                    }
                },
                "base": {
                    "ref": "main",
                    "sha": "def456",
                    "repo": {
                        "id": 456,
                        "name": "repo",
                        "full_name": "owner/repo"
                    }
                },
                "draft": false,
                "merged": false,
                "mergeable": true,
                "merge_commit_sha": null,
                "assignees": [],
                "requested_reviewers": [],
                "labels": [],
                "milestone": null,
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z",
                "closed_at": null,
                "merged_at": null,
                "html_url": "https://github.com/owner/repo/pull/42"
            })))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let pr = client
            .pull_requests()
            .get("owner", "repo", 42)
            .await
            .unwrap();

        assert_eq!(pr.number, 42);
        assert_eq!(pr.title, "Test PR");
    }

    /// Verify get_pull_request returns NotFound for non-existent PR.
    ///
    /// Tests: Error handling for missing resources
    #[tokio::test]
    async fn test_get_pull_request_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/repos/owner/repo/pulls/999"))
            .respond_with(ResponseTemplate::new(404))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client.pull_requests().get("owner", "repo", 999).await;

        assert!(matches!(result, Err(ApiError::NotFound)));
    }

    /// Verify create_pull_request creates new PR via GitHub API.
    ///
    /// Tests: docs/spec/assertions.md #10
    #[tokio::test]
    async fn test_create_pull_request() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/repos/owner/repo/pulls"))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "id": 1,
                "node_id": "PR_1",
                "number": 42,
                "title": "New Feature",
                "body": "Feature description",
                "state": "open",
                "user": {
                    "login": "testuser",
                    "id": 123,
                    "node_id": "U_123",
                    "type": "User"
                },
                "head": {
                    "ref": "feature-branch",
                    "sha": "abc123",
                    "repo": {
                        "id": 456,
                        "name": "repo",
                        "full_name": "owner/repo"
                    }
                },
                "base": {
                    "ref": "main",
                    "sha": "def456",
                    "repo": {
                        "id": 456,
                        "name": "repo",
                        "full_name": "owner/repo"
                    }
                },
                "draft": false,
                "merged": false,
                "mergeable": null,
                "merge_commit_sha": null,
                "assignees": [],
                "requested_reviewers": [],
                "labels": [],
                "milestone": null,
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z",
                "closed_at": null,
                "merged_at": null,
                "html_url": "https://github.com/owner/repo/pull/42"
            })))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let request = CreatePullRequestRequest {
            title: "New Feature".to_string(),
            head: "feature-branch".to_string(),
            base: "main".to_string(),
            body: Some("Feature description".to_string()),
            draft: None,
            milestone: None,
            maintainer_can_modify: None,
        };

        let pr = client
            .pull_requests()
            .create("owner", "repo", request)
            .await
            .unwrap();

        assert_eq!(pr.number, 42);
        assert_eq!(pr.title, "New Feature");
    }
}

mod milestone_operations {
    use super::*;

    fn pr_json(milestone_number: Option<u64>) -> serde_json::Value {
        serde_json::json!({
            "id": 1,
            "node_id": "PR_1",
            "number": 42,
            "title": "Test PR",
            "body": null,
            "state": "open",
            "user": {
                "login": "testuser",
                "id": 123,
                "node_id": "U_123",
                "type": "User"
            },
            "head": {
                "ref": "feature-branch",
                "sha": "abc123",
                "repo": {
                    "id": 456,
                    "name": "repo",
                    "full_name": "owner/repo"
                }
            },
            "base": {
                "ref": "main",
                "sha": "def456",
                "repo": {
                    "id": 456,
                    "name": "repo",
                    "full_name": "owner/repo"
                }
            },
            "draft": false,
            "merged": false,
            "mergeable": null,
            "merge_commit_sha": null,
            "assignees": [],
            "requested_reviewers": [],
            "labels": [],
            "milestone": milestone_number.map(|n| serde_json::json!({
                "id": n,
                "node_id": "MI_1",
                "number": n,
                "title": "v1.0",
                "description": null,
                "state": "open",
                "open_issues": 0,
                "closed_issues": 0,
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z",
                "due_on": null,
                "closed_at": null,
                "html_url": "https://github.com/owner/repo/milestone/1",
                "url": "https://api.github.com/repos/owner/repo/milestones/1",
                "labels_url": "https://api.github.com/repos/owner/repo/milestones/1/labels",
                "creator": {
                    "login": "testuser",
                    "id": 123,
                    "node_id": "U_123",
                    "type": "User"
                }
            })),
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z",
            "closed_at": null,
            "merged_at": null,
            "html_url": "https://github.com/owner/repo/pull/42"
        })
    }

    fn issue_json(milestone_number: Option<u64>) -> serde_json::Value {
        serde_json::json!({
            "id": 1,
            "node_id": "I_1",
            "number": 42,
            "title": "Test PR",
            "body": null,
            "state": "open",
            "locked": false,
            "user": {
                "login": "testuser",
                "id": 123,
                "node_id": "U_123",
                "type": "User"
            },
            "assignees": [],
            "labels": [],
            "milestone": milestone_number.map(|n| serde_json::json!({
                "id": n,
                "node_id": "MI_1",
                "number": n,
                "title": "v1.0",
                "description": null,
                "state": "open",
                "open_issues": 0,
                "closed_issues": 0,
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z",
                "due_on": null,
                "closed_at": null,
                "html_url": "https://github.com/owner/repo/milestone/1",
                "url": "https://api.github.com/repos/owner/repo/milestones/1",
                "labels_url": "https://api.github.com/repos/owner/repo/milestones/1/labels",
                "creator": {
                    "login": "testuser",
                    "id": 123,
                    "node_id": "U_123",
                    "type": "User"
                }
            })),
            "comments": 0,
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z",
            "closed_at": null,
            "html_url": "https://github.com/owner/repo/issues/42"
        })
    }

    /// Verify set_milestone delegates to the Issues API, not the Pulls API.
    ///
    /// GitHub's Pulls API silently ignores the milestone field; the Issues API
    /// (PATCH /repos/{owner}/{repo}/issues/{number}) is the correct endpoint.
    /// After setting the milestone via the Issues API the PR is re-fetched.
    #[tokio::test]
    async fn test_set_milestone_uses_issues_api() {
        let mock_server = MockServer::start().await;

        // The Issues API PATCH must be called to set the milestone.
        Mock::given(method("PATCH"))
            .and(path("/repos/owner/repo/issues/42"))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(issue_json(Some(7))))
            .mount(&mock_server)
            .await;

        // After the Issues API call the PR is re-fetched.
        Mock::given(method("GET"))
            .and(path("/repos/owner/repo/pulls/42"))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(pr_json(Some(7))))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let pr = client
            .pull_requests()
            .set_milestone("owner", "repo", 42, Some(7))
            .await
            .unwrap();

        assert_eq!(pr.number, 42);
        assert!(pr.milestone.is_some());
        assert_eq!(pr.milestone.unwrap().number, 7);
    }

    /// Verify set_milestone with None clears the milestone via the Issues API.
    #[tokio::test]
    async fn test_set_milestone_clear_uses_issues_api() {
        let mock_server = MockServer::start().await;

        Mock::given(method("PATCH"))
            .and(path("/repos/owner/repo/issues/42"))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(issue_json(None)))
            .mount(&mock_server)
            .await;

        Mock::given(method("GET"))
            .and(path("/repos/owner/repo/pulls/42"))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(pr_json(None)))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let pr = client
            .pull_requests()
            .set_milestone("owner", "repo", 42, None)
            .await
            .unwrap();

        assert_eq!(pr.number, 42);
        assert!(pr.milestone.is_none());
    }

    /// Verify set_milestone propagates errors from the Issues API.
    #[tokio::test]
    async fn test_set_milestone_propagates_issues_api_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("PATCH"))
            .and(path("/repos/owner/repo/issues/42"))
            .respond_with(ResponseTemplate::new(404))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client
            .pull_requests()
            .set_milestone("owner", "repo", 42, Some(7))
            .await;

        assert!(matches!(result, Err(ApiError::NotFound)));
    }
}

mod comment_operations {
    use super::*;

    /// Verify update_comment patches an existing pull request comment and returns it.
    ///
    /// Tests PATCH /repos/{owner}/{repo}/issues/comments/{id} endpoint.
    #[tokio::test]
    async fn test_update_comment() {
        let mock_server = MockServer::start().await;

        let updated_comment_json = serde_json::json!({
            "id": 1,
            "node_id": "MDEyOklzc3VlQ29tbWVudDE=",
            "body": "Updated comment",
            "user": {"login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "type": "User"},
            "created_at": "2011-04-14T16:00:49Z",
            "updated_at": "2011-04-14T17:00:49Z",
            "html_url": "https://github.com/octocat/Hello-World/pull/1#issuecomment-1"
        });

        Mock::given(method("PATCH"))
            .and(path("/repos/octocat/Hello-World/issues/comments/1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(updated_comment_json))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let request = UpdatePullRequestCommentRequest {
            body: "Updated comment".to_string(),
        };

        let result = client
            .pull_requests()
            .update_comment("octocat", "Hello-World", 1, request)
            .await;

        assert!(result.is_ok());
        let comment = result.unwrap();
        assert_eq!(comment.id, 1);
        assert_eq!(comment.body, "Updated comment");
    }

    /// Verify delete_comment removes a pull request comment.
    ///
    /// Tests DELETE /repos/{owner}/{repo}/issues/comments/{id} endpoint.
    #[tokio::test]
    async fn test_delete_comment() {
        let mock_server = MockServer::start().await;

        Mock::given(method("DELETE"))
            .and(path("/repos/octocat/Hello-World/issues/comments/1"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client
            .pull_requests()
            .delete_comment("octocat", "Hello-World", 1)
            .await;

        assert!(result.is_ok());
    }

    /// Verify update_comment returns NotFound for a non-existent comment.
    ///
    /// Tests PATCH /repos/{owner}/{repo}/issues/comments/{id} returning 404.
    #[tokio::test]
    async fn test_update_comment_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("PATCH"))
            .and(path("/repos/octocat/Hello-World/issues/comments/999"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "message": "Not Found",
                "documentation_url": "https://docs.github.com/rest/issues/comments#update-an-issue-comment"
            })))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token("test-token");
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let request = UpdatePullRequestCommentRequest {
            body: "text".to_string(),
        };

        let result = client
            .pull_requests()
            .update_comment("octocat", "Hello-World", 999, request)
            .await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ApiError::NotFound));
    }
}

mod label_operations {
    use super::*;

    fn label_json() -> serde_json::Value {
        serde_json::json!({
            "id": 1,
            "node_id": "MDU6TGFiZWwx",
            "name": "bug",
            "description": "Something isn't working",
            "color": "d73a4a",
            "default": true
        })
    }

    /// Verify add_labels sends correct JSON object body and returns labels.
    ///
    /// Tests POST /repos/{owner}/{repo}/issues/{number}/labels with {"labels":[…]} body.
    #[tokio::test]
    async fn test_add_labels() {
        let mock_server = MockServer::start().await;
        let test_token = "ghs_test_token";

        Mock::given(method("POST"))
            .and(path("/repos/octocat/Hello-World/issues/42/labels"))
            .and(wiremock::matchers::body_json(
                serde_json::json!({"labels": ["bug"]}),
            ))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([label_json()])),
            )
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token(test_token);
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client
            .pull_requests()
            .add_labels("octocat", "Hello-World", 42, vec!["bug".to_string()])
            .await;

        assert!(result.is_ok());
        let labels = result.unwrap();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].name, "bug");
    }

    /// Verify replace_labels sends a PUT request with correct JSON body.
    ///
    /// Tests PUT /repos/{owner}/{repo}/issues/{number}/labels with {"labels":[…]} body.
    #[tokio::test]
    async fn test_replace_labels() {
        let mock_server = MockServer::start().await;
        let test_token = "ghs_test_token";

        let feature_label = serde_json::json!({
            "id": 2,
            "node_id": "MDU6TGFiZWwy",
            "name": "feature",
            "description": "New feature",
            "color": "0075ca",
            "default": false
        });

        Mock::given(method("PUT"))
            .and(path("/repos/octocat/Hello-World/issues/42/labels"))
            .and(wiremock::matchers::body_json(
                serde_json::json!({"labels": ["feature"]}),
            ))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([feature_label])),
            )
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token(test_token);
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client
            .pull_requests()
            .replace_labels("octocat", "Hello-World", 42, vec!["feature".to_string()])
            .await;

        assert!(result.is_ok());
        let labels = result.unwrap();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].name, "feature");
    }

    /// Verify replace_labels with empty vec clears all labels.
    ///
    /// Tests PUT /repos/{owner}/{repo}/issues/{number}/labels with {"labels":[]} body.
    #[tokio::test]
    async fn test_replace_labels_clears_all() {
        let mock_server = MockServer::start().await;
        let test_token = "ghs_test_token";

        Mock::given(method("PUT"))
            .and(path("/repos/octocat/Hello-World/issues/42/labels"))
            .and(wiremock::matchers::body_json(
                serde_json::json!({"labels": []}),
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token(test_token);
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client
            .pull_requests()
            .replace_labels("octocat", "Hello-World", 42, vec![])
            .await;

        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    /// Verify remove_label sends a DELETE request and returns remaining labels.
    ///
    /// Tests DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name}.
    /// The GitHub endpoint responds with the remaining labels as a JSON array.
    #[tokio::test]
    async fn test_remove_label() {
        let mock_server = MockServer::start().await;
        let test_token = "ghs_test_token";

        let remaining_label = serde_json::json!({
            "id": 2,
            "node_id": "MDU6TGFiZWwy",
            "name": "enhancement",
            "description": "New feature or request",
            "color": "a2eeef",
            "default": true
        });

        Mock::given(method("DELETE"))
            .and(path("/repos/octocat/Hello-World/issues/42/labels/bug"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([remaining_label])),
            )
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token(test_token);
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client
            .pull_requests()
            .remove_label("octocat", "Hello-World", 42, "bug")
            .await;

        assert!(result.is_ok());
        let labels = result.unwrap();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].name, "enhancement");
    }

    /// Verify remove_label returns NotFound when the label is not applied to the PR.
    ///
    /// Tests DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name} returning 404.
    #[tokio::test]
    async fn test_remove_label_not_found() {
        let mock_server = MockServer::start().await;
        let test_token = "ghs_test_token";

        Mock::given(method("DELETE"))
            .and(path(
                "/repos/octocat/Hello-World/issues/42/labels/nonexistent",
            ))
            .respond_with(ResponseTemplate::new(404))
            .mount(&mock_server)
            .await;

        let auth = MockAuthProvider::new_with_token(test_token);
        let github_client = GitHubClient::builder(auth)
            .config(ClientConfig::default().with_github_api_url(mock_server.uri()))
            .build()
            .unwrap();
        let client = github_client
            .installation_by_id(InstallationId::new(12345))
            .await
            .unwrap();

        let result = client
            .pull_requests()
            .remove_label("octocat", "Hello-World", 42, "nonexistent")
            .await;

        assert!(matches!(result, Err(ApiError::NotFound)));
    }
}