linear-api 0.1.0

Unofficial async Rust client for the Linear GraphQL API (API-key auth)
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
//! Issue CRUD, list/search, batch create, and label convenience operations —
//! [`IssuesService`], obtained via [`LinearClient::issues`].

use bon::Builder;
use serde::Deserialize;

use crate::client::LinearClient;
use crate::error::{Error, Result};
use crate::filter::IssueFilter;
use crate::ids::{
    CycleId, IssueId, IssueRef, LabelId, ProjectId, ProjectMilestoneId, TeamId, TemplateId, UserId,
    WorkflowStateId,
};
use crate::pagination::{Page, PageInfo};
use crate::types::{
    IssueRelationType, IssueStub, LabelRef, MilestoneRef, PaginationOrderBy, Priority, ProjectRef,
    StateRef, TeamRef, TimelessDate, Undefinable, UserRef,
};

/// A Linear issue with its commonly needed references embedded (state, team,
/// people, labels, project placement, parent, and relation summaries).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Issue {
    /// Issue ID (UUID).
    pub id: IssueId,
    /// Human identifier, e.g. `"ENG-123"`.
    pub identifier: String,
    /// Issue number within its team (a `Float` on the wire).
    pub number: f64,
    /// Issue title.
    pub title: String,
    /// Issue description in markdown, when set.
    pub description: Option<String>,
    /// URL of the issue in the Linear app.
    pub url: String,
    /// Suggested VCS branch name for this issue.
    pub branch_name: String,
    /// Priority (0 = none … 4 = low).
    pub priority: Priority,
    /// Human-readable priority label, e.g. `"High"`.
    pub priority_label: String,
    /// Estimate in the team's chosen scale, when set.
    pub estimate: Option<f64>,
    /// Due date, when set.
    pub due_date: Option<TimelessDate>,
    /// Board sort order.
    pub sort_order: f64,
    /// Current workflow state.
    pub state: StateRef,
    /// Owning team.
    pub team: TeamRef,
    /// Assignee, when set.
    pub assignee: Option<UserRef>,
    /// Creator; absent for issues created by integrations.
    pub creator: Option<UserRef>,
    /// Labels attached to the issue (first 50).
    #[serde(deserialize_with = "crate::types::nodes")]
    pub labels: Vec<LabelRef>,
    /// Project the issue belongs to, when any.
    pub project: Option<ProjectRef>,
    /// Project milestone the issue is slotted into, when any.
    pub project_milestone: Option<MilestoneRef>,
    /// Parent issue, when this is a sub-issue.
    pub parent: Option<IssueStub>,
    /// Outgoing relations (first 10): this issue is the source, e.g. it
    /// *blocks* [`OutgoingRelation::related_issue`].
    #[serde(deserialize_with = "crate::types::nodes")]
    pub relations: Vec<OutgoingRelation>,
    /// Incoming relations (first 10): this issue is the target, e.g. it is
    /// *blocked by* [`IncomingRelation::issue`].
    #[serde(deserialize_with = "crate::types::nodes")]
    pub inverse_relations: Vec<IncomingRelation>,
    /// When the issue was created.
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
    /// When the issue was last updated.
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
    /// When the issue was completed, when it was.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub completed_at: Option<time::OffsetDateTime>,
    /// When the issue was canceled, when it was.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub canceled_at: Option<time::OffsetDateTime>,
    /// When work on the issue started, when it did.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub started_at: Option<time::OffsetDateTime>,
    /// When the issue was archived, when it was.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub archived_at: Option<time::OffsetDateTime>,
}

impl Issue {
    /// Issues **this issue blocks**: outgoing relations of type
    /// [`IssueRelationType::Blocks`], yielding their
    /// [`related_issue`](OutgoingRelation::related_issue).
    ///
    /// Relation semantics: a `blocks` relation means `issueId` blocks
    /// `relatedIssueId`; `relations` holds the outgoing side and
    /// `inverseRelations` the incoming side.
    pub fn blocks(&self) -> Vec<&IssueStub> {
        self.relations
            .iter()
            .filter(|relation| relation.relation_type == IssueRelationType::Blocks)
            .map(|relation| &relation.related_issue)
            .collect()
    }

    /// Issues **this issue is blocked by**: incoming relations of type
    /// [`IssueRelationType::Blocks`], yielding their
    /// [`issue`](IncomingRelation::issue) (the blocker).
    pub fn blocked_by(&self) -> Vec<&IssueStub> {
        self.inverse_relations
            .iter()
            .filter(|relation| relation.relation_type == IssueRelationType::Blocks)
            .map(|relation| &relation.issue)
            .collect()
    }
}

/// An outgoing issue relation: the owning issue is the source (e.g. it
/// *blocks* [`related_issue`](Self::related_issue)).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct OutgoingRelation {
    /// The relation type.
    #[serde(rename = "type")]
    pub relation_type: IssueRelationType,
    /// The target of the relation.
    pub related_issue: IssueStub,
}

/// An incoming issue relation: the owning issue is the target (e.g. it is
/// *blocked by* [`issue`](Self::issue)).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IncomingRelation {
    /// The relation type.
    #[serde(rename = "type")]
    pub relation_type: IssueRelationType,
    /// The source of the relation.
    pub issue: IssueStub,
}

/// One hit from [`IssuesService::search`]. This is Linear's own
/// `IssueSearchResult` GraphQL type (not `Issue`), so it carries a smaller
/// field set plus search [`metadata`](Self::metadata).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IssueSearchResult {
    /// Issue ID (UUID).
    pub id: IssueId,
    /// Human identifier, e.g. `"ENG-123"`.
    pub identifier: String,
    /// Issue title.
    pub title: String,
    /// Issue description in markdown, when set.
    pub description: Option<String>,
    /// URL of the issue in the Linear app.
    pub url: String,
    /// Priority (0 = none … 4 = low).
    pub priority: Priority,
    /// Estimate in the team's chosen scale, when set.
    pub estimate: Option<f64>,
    /// Current workflow state.
    pub state: StateRef,
    /// Owning team.
    pub team: TeamRef,
    /// Assignee, when set.
    pub assignee: Option<UserRef>,
    /// Labels attached to the issue (first 50).
    #[serde(deserialize_with = "crate::types::nodes")]
    pub labels: Vec<LabelRef>,
    /// Search-engine metadata about the match (relevance data; shape is not
    /// part of Linear's stable API).
    pub metadata: serde_json::Value,
    /// When the issue was created.
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
    /// When the issue was last updated.
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
}

/// Request for [`IssuesService::list`]. All fields are optional; the server
/// page size defaults to 50.
///
/// ```
/// use linear_api::IssueFilter;
/// use linear_api::issues::ListIssuesRequest;
///
/// let request = ListIssuesRequest::builder()
///     .filter(IssueFilter::default())
///     .first(25)
///     .build();
/// ```
#[derive(Debug, Clone, Default, serde::Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ListIssuesRequest {
    /// Filter the returned issues.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter: Option<IssueFilter>,
    /// Page size (server default 50). Larger pages multiply query complexity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first: Option<i32>,
    /// Cursor to continue from (a previous page's `end_cursor`).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub after: Option<String>,
    /// Include archived issues (server default `false`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_archived: Option<bool>,
    /// Pagination order (server default: created-at).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_by: Option<PaginationOrderBy>,
}

/// Request for [`IssuesService::search`]. Only `term` is required.
///
/// ```
/// use linear_api::issues::SearchIssuesRequest;
///
/// let request = SearchIssuesRequest::builder()
///     .term("flux capacitor")
///     .first(10)
///     .build();
/// ```
#[derive(Debug, Clone, serde::Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SearchIssuesRequest {
    /// Full-text search term (required).
    #[builder(into)]
    pub term: String,
    /// Filter the searched issues.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter: Option<IssueFilter>,
    /// Page size (server default 50).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first: Option<i32>,
    /// Cursor to continue from (a previous page's `end_cursor`).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub after: Option<String>,
}

/// Input for [`IssuesService::create`] and [`IssuesService::batch_create`].
/// `team_id` and `title` are required; unset optional fields are omitted from
/// the request.
///
/// ```
/// use linear_api::issues::IssueCreateInput;
/// use linear_api::{Priority, TeamId};
///
/// let input = IssueCreateInput::builder()
///     .team_id(TeamId::new("team-1"))
///     .title("Fix the flux capacitor")
///     .priority(Priority::High)
///     .build();
/// ```
#[derive(Debug, Clone, serde::Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IssueCreateInput {
    /// Team to create the issue in (required).
    #[builder(into)]
    pub team_id: TeamId,
    /// Issue title (required).
    #[builder(into)]
    pub title: String,
    /// Description in markdown.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub description: Option<String>,
    /// Assignee.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignee_id: Option<UserId>,
    /// Workflow state (defaults to the team's first state).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state_id: Option<WorkflowStateId>,
    /// Priority.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<Priority>,
    /// Estimate in the team's chosen scale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub estimate: Option<i64>,
    /// Labels to attach.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label_ids: Option<Vec<LabelId>>,
    /// Project to place the issue in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_id: Option<ProjectId>,
    /// Project milestone to slot the issue into.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_milestone_id: Option<ProjectMilestoneId>,
    /// Cycle to schedule the issue into.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cycle_id: Option<CycleId>,
    /// Parent issue (makes this a sub-issue).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<IssueId>,
    /// Due date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub due_date: Option<TimelessDate>,
    /// Board sort order.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_order: Option<f64>,
    /// Users to subscribe to the issue.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscriber_ids: Option<Vec<UserId>>,
    /// Template to apply.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template_id: Option<TemplateId>,
    /// Display name to create the issue as (app credentials only).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub create_as_user: Option<String>,
}

/// Input for [`IssuesService::update`]. Every field is optional.
///
/// Plain `Option` fields are *set-only*; [`Undefinable`] fields are
/// tri-state: leave them [`Undefinable::Undefined`] (the default) to keep the
/// current value, set [`Undefinable::Null`] to **clear** it, or a value to
/// change it.
///
/// For labels, prefer [`added_label_ids`](Self::added_label_ids) /
/// [`removed_label_ids`](Self::removed_label_ids) over replacing the whole
/// set with [`label_ids`](Self::label_ids) — the delta form cannot clobber
/// labels added concurrently by someone else.
///
/// ```
/// use linear_api::Undefinable;
/// use linear_api::issues::IssueUpdateInput;
///
/// // Set the estimate, clear the assignee, leave everything else unchanged.
/// let input = IssueUpdateInput::builder()
///     .estimate(3)
///     .assignee_id(Undefinable::Null)
///     .build();
/// ```
#[derive(Debug, Clone, Default, serde::Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IssueUpdateInput {
    /// New title.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub title: Option<String>,
    /// New workflow state.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state_id: Option<WorkflowStateId>,
    /// New priority.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<Priority>,
    /// New board sort order.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_order: Option<f64>,
    /// Replace the full label set. Prefer
    /// [`added_label_ids`](Self::added_label_ids) /
    /// [`removed_label_ids`](Self::removed_label_ids).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label_ids: Option<Vec<LabelId>>,
    /// Labels to add, keeping existing ones.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub added_label_ids: Option<Vec<LabelId>>,
    /// Labels to remove, keeping the rest.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub removed_label_ids: Option<Vec<LabelId>>,
    /// Description in markdown.
    ///
    /// Live-verified server quirk: Linear **ignores `null`** for this
    /// document-backed field — [`Undefinable::Null`] is a no-op here. To
    /// clear the description, set it to an empty string.
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub description: Undefinable<String>,
    /// Assignee ([`Undefinable::Null`] unassigns).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub assignee_id: Undefinable<UserId>,
    /// Estimate ([`Undefinable::Null`] clears it).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub estimate: Undefinable<i64>,
    /// Project ([`Undefinable::Null`] removes the issue from its project).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub project_id: Undefinable<ProjectId>,
    /// Project milestone ([`Undefinable::Null`] clears it).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub project_milestone_id: Undefinable<ProjectMilestoneId>,
    /// Cycle ([`Undefinable::Null`] removes the issue from its cycle).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub cycle_id: Undefinable<CycleId>,
    /// Parent issue ([`Undefinable::Null`] promotes it to a top-level issue).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub parent_id: Undefinable<IssueId>,
    /// Due date ([`Undefinable::Null`] clears it).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub due_date: Undefinable<TimelessDate>,
}

/// Shared tail for every document that spreads `...IssueFields`. A macro (not
/// a `const`) so it can be `concat!`-ed into `&'static str` documents.
macro_rules! issue_fields_fragments {
    () => {
        " fragment IssueFields on Issue { id identifier number title description url branchName \
         priority priorityLabel estimate dueDate sortOrder createdAt updatedAt completedAt \
         canceledAt startedAt archivedAt state { ...StateRefFields } team { ...TeamRefFields } \
         assignee { ...UserRefFields } creator { ...UserRefFields } \
         labels(first: 50) { nodes { ...LabelRefFields } } project { ...ProjectRefFields } \
         projectMilestone { ...MilestoneRefFields } parent { ...IssueStubFields } \
         relations(first: 10) { nodes { type relatedIssue { ...IssueStubFields } } } \
         inverseRelations(first: 10) { nodes { type issue { ...IssueStubFields } } } } \
         fragment UserRefFields on User { id name displayName } \
         fragment TeamRefFields on Team { id key name } \
         fragment ProjectRefFields on Project { id name } \
         fragment IssueStubFields on Issue { id identifier title } \
         fragment LabelRefFields on IssueLabel { id name color } \
         fragment StateRefFields on WorkflowState { id name type color } \
         fragment MilestoneRefFields on ProjectMilestone { id name }"
    };
}

const ISSUE_GET: &str = concat!(
    "query IssueGet($id: String!) { issue(id: $id) { ...IssueFields } }",
    issue_fields_fragments!()
);

const ISSUE_LIST: &str = concat!(
    "query IssueList($filter: IssueFilter, $first: Int, $after: String, \
     $includeArchived: Boolean, $orderBy: PaginationOrderBy) { \
     issues(filter: $filter, first: $first, after: $after, \
     includeArchived: $includeArchived, orderBy: $orderBy) { \
     nodes { ...IssueFields } \
     pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } }",
    issue_fields_fragments!()
);

// `IssueSearchResult` is its own GraphQL type — a fragment on `Issue` cannot
// spread into it, so its selection is written inline.
const ISSUE_SEARCH: &str = "query IssueSearch($term: String!, $filter: IssueFilter, $first: Int, $after: String) { \
     searchIssues(term: $term, filter: $filter, first: $first, after: $after) { \
     nodes { id identifier title description url priority estimate metadata createdAt updatedAt \
     state { id name type color } team { id key name } assignee { id name displayName } \
     labels(first: 50) { nodes { id name color } } } \
     pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } }";

const ISSUE_CREATE: &str = concat!(
    "mutation IssueCreate($input: IssueCreateInput!) { \
     issueCreate(input: $input) { success issue { ...IssueFields } } }",
    issue_fields_fragments!()
);

const ISSUE_BATCH_CREATE: &str = concat!(
    "mutation IssueBatchCreate($input: IssueBatchCreateInput!) { \
     issueBatchCreate(input: $input) { success issues { ...IssueFields } } }",
    issue_fields_fragments!()
);

const ISSUE_UPDATE: &str = concat!(
    "mutation IssueUpdate($id: String!, $input: IssueUpdateInput!) { \
     issueUpdate(id: $id, input: $input) { success issue { ...IssueFields } } }",
    issue_fields_fragments!()
);

const ISSUE_ARCHIVE: &str =
    "mutation IssueArchive($id: String!) { issueArchive(id: $id) { success } }";

const ISSUE_DELETE: &str =
    "mutation IssueDelete($id: String!) { issueDelete(id: $id) { success } }";

const ISSUE_ADD_LABEL: &str = concat!(
    "mutation IssueAddLabel($id: String!, $labelId: String!) { \
     issueAddLabel(id: $id, labelId: $labelId) { success issue { ...IssueFields } } }",
    issue_fields_fragments!()
);

const ISSUE_REMOVE_LABEL: &str = concat!(
    "mutation IssueRemoveLabel($id: String!, $labelId: String!) { \
     issueRemoveLabel(id: $id, labelId: $labelId) { success issue { ...IssueFields } } }",
    issue_fields_fragments!()
);

pub(crate) const DOCUMENTS: &[(&str, &str)] = &[
    ("IssueGet", ISSUE_GET),
    ("IssueList", ISSUE_LIST),
    ("IssueSearch", ISSUE_SEARCH),
    ("IssueCreate", ISSUE_CREATE),
    ("IssueBatchCreate", ISSUE_BATCH_CREATE),
    ("IssueUpdate", ISSUE_UPDATE),
    ("IssueArchive", ISSUE_ARCHIVE),
    ("IssueDelete", ISSUE_DELETE),
    ("IssueAddLabel", ISSUE_ADD_LABEL),
    ("IssueRemoveLabel", ISSUE_REMOVE_LABEL),
];

/// `issueCreate` / `issueUpdate` / `issueAddLabel` / `issueRemoveLabel`
/// payload.
#[derive(Deserialize)]
struct IssuePayload {
    success: bool,
    issue: Option<Issue>,
}

fn payload_issue(operation: &'static str, payload: IssuePayload) -> Result<Issue> {
    crate::types::ensure_success(operation, payload.success)?;
    payload.issue.ok_or(Error::MissingData { operation })
}

/// `issueArchive` / `issueDelete` payload (only `success` is selected).
#[derive(Deserialize)]
struct SuccessPayload {
    success: bool,
}

/// Issue operations. Obtained via [`LinearClient::issues`]; `Copy`, so it can
/// be freely captured by pagination closures.
#[derive(Clone, Copy)]
pub struct IssuesService<'a> {
    client: &'a LinearClient,
}

impl LinearClient {
    /// Issue operations: CRUD, list/search, batch create, and label
    /// convenience mutations.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let issue = client
    ///     .issues()
    ///     .get(linear_api::IssueRef::identifier("ENG-123"))
    ///     .await?;
    /// println!("{}: {}", issue.identifier, issue.title);
    /// # Ok(()) }
    /// ```
    pub fn issues(&self) -> IssuesService<'_> {
        IssuesService { client: self }
    }
}

impl<'a> IssuesService<'a> {
    /// Fetches one issue by UUID or human identifier.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let issue = client
    ///     .issues()
    ///     .get(linear_api::IssueRef::identifier("ENG-123"))
    ///     .await?;
    /// assert_eq!(issue.identifier, "ENG-123");
    /// # Ok(()) }
    /// ```
    pub async fn get(&self, issue: impl Into<IssueRef>) -> Result<Issue> {
        #[derive(Deserialize)]
        struct Data {
            issue: Issue,
        }
        let issue = issue.into();
        let data: Data = self
            .client
            .query(
                "IssueGet",
                ISSUE_GET,
                serde_json::json!({ "id": issue.api_string() }),
            )
            .await?;
        Ok(data.issue)
    }

    /// Fetches one page of issues.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::issues::ListIssuesRequest;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let page = client
    ///     .issues()
    ///     .list(ListIssuesRequest::builder().first(25).build())
    ///     .await?;
    /// println!("{} issues, more: {}", page.nodes.len(), page.page_info.has_next_page);
    /// # Ok(()) }
    /// ```
    pub async fn list(&self, req: ListIssuesRequest) -> Result<Page<Issue>> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Connection {
            nodes: Vec<Issue>,
            page_info: PageInfo,
        }
        #[derive(Deserialize)]
        struct Data {
            issues: Connection,
        }
        let data: Data = self.client.query("IssueList", ISSUE_LIST, req).await?;
        Ok(Page {
            nodes: data.issues.nodes,
            page_info: data.issues.page_info,
        })
    }

    /// Lazily streams issues across pages, starting from `req.after` when
    /// set (the cursor then advances page by page).
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use futures::TryStreamExt;
    /// use linear_api::issues::ListIssuesRequest;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let issues = client.issues();
    /// let mut stream = std::pin::pin!(
    ///     issues.list_stream(ListIssuesRequest::builder().first(50).build())
    /// );
    /// while let Some(issue) = stream.try_next().await? {
    ///     println!("{}: {}", issue.identifier, issue.title);
    /// }
    /// # Ok(()) }
    /// ```
    pub fn list_stream(
        &self,
        req: ListIssuesRequest,
    ) -> impl futures::Stream<Item = Result<Issue>> + 'a {
        let service = *self;
        crate::pagination::paginate(move |cursor| {
            let mut req = req.clone();
            // The first call keeps a caller-seeded `req.after`; later calls
            // advance to each page's end cursor.
            if cursor.is_some() {
                req.after = cursor;
            }
            async move { service.list(req).await }
        })
    }

    /// Full-text search over issues via the `searchIssues` API (rate-limited
    /// by Linear to 30 requests per minute).
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::issues::SearchIssuesRequest;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let hits = client
    ///     .issues()
    ///     .search(SearchIssuesRequest::builder().term("flux capacitor").build())
    ///     .await?;
    /// for hit in &hits.nodes {
    ///     println!("{}: {}", hit.identifier, hit.title);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn search(&self, req: SearchIssuesRequest) -> Result<Page<IssueSearchResult>> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Connection {
            nodes: Vec<IssueSearchResult>,
            page_info: PageInfo,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            search_issues: Connection,
        }
        let data: Data = self.client.query("IssueSearch", ISSUE_SEARCH, req).await?;
        Ok(Page {
            nodes: data.search_issues.nodes,
            page_info: data.search_issues.page_info,
        })
    }

    /// Creates one issue.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::TeamId;
    /// use linear_api::issues::IssueCreateInput;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let issue = client
    ///     .issues()
    ///     .create(
    ///         IssueCreateInput::builder()
    ///             .team_id(TeamId::new("9cfb482a-81e3-4154-b5b9-2c805e70a02d"))
    ///             .title("Fix the flux capacitor")
    ///             .build(),
    ///     )
    ///     .await?;
    /// println!("created {}", issue.identifier);
    /// # Ok(()) }
    /// ```
    pub async fn create(&self, input: IssueCreateInput) -> Result<Issue> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_create: IssuePayload,
        }
        let data: Data = self
            .client
            .mutation(
                "IssueCreate",
                ISSUE_CREATE,
                serde_json::json!({ "input": input }),
            )
            .await?;
        payload_issue("IssueCreate", data.issue_create)
    }

    /// Creates several issues in one transaction (`issueBatchCreate`).
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::TeamId;
    /// use linear_api::issues::IssueCreateInput;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let team = TeamId::new("9cfb482a-81e3-4154-b5b9-2c805e70a02d");
    /// let issues = client
    ///     .issues()
    ///     .batch_create(vec![
    ///         IssueCreateInput::builder().team_id(team.clone()).title("One").build(),
    ///         IssueCreateInput::builder().team_id(team).title("Two").build(),
    ///     ])
    ///     .await?;
    /// assert_eq!(issues.len(), 2);
    /// # Ok(()) }
    /// ```
    pub async fn batch_create(&self, issues: Vec<IssueCreateInput>) -> Result<Vec<Issue>> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
            issues: Vec<Issue>,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_batch_create: Payload,
        }
        let data: Data = self
            .client
            .mutation(
                "IssueBatchCreate",
                ISSUE_BATCH_CREATE,
                serde_json::json!({ "input": { "issues": issues } }),
            )
            .await?;
        crate::types::ensure_success("IssueBatchCreate", data.issue_batch_create.success)?;
        Ok(data.issue_batch_create.issues)
    }

    /// Updates one issue by UUID or human identifier. See
    /// [`IssueUpdateInput`] for set/clear/leave-unchanged semantics.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// use linear_api::issues::IssueUpdateInput;
    /// use linear_api::{IssueRef, Undefinable};
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let issue = client
    ///     .issues()
    ///     .update(
    ///         IssueRef::identifier("ENG-123"),
    ///         IssueUpdateInput::builder()
    ///             .title("Fix the flux capacitor for real")
    ///             .due_date(Undefinable::Null) // clear the due date
    ///             .build(),
    ///     )
    ///     .await?;
    /// println!("updated {}", issue.identifier);
    /// # Ok(()) }
    /// ```
    pub async fn update(
        &self,
        issue: impl Into<IssueRef>,
        input: IssueUpdateInput,
    ) -> Result<Issue> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_update: IssuePayload,
        }
        let issue = issue.into();
        let data: Data = self
            .client
            .mutation(
                "IssueUpdate",
                ISSUE_UPDATE,
                serde_json::json!({ "id": issue.api_string(), "input": input }),
            )
            .await?;
        payload_issue("IssueUpdate", data.issue_update)
    }

    /// Archives one issue.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// client
    ///     .issues()
    ///     .archive(linear_api::IssueRef::identifier("ENG-123"))
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn archive(&self, issue: impl Into<IssueRef>) -> Result<()> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_archive: SuccessPayload,
        }
        let issue = issue.into();
        let data: Data = self
            .client
            .mutation(
                "IssueArchive",
                ISSUE_ARCHIVE,
                serde_json::json!({ "id": issue.api_string() }),
            )
            .await?;
        crate::types::ensure_success("IssueArchive", data.issue_archive.success)
    }

    /// Deletes (trashes) one issue. Linear keeps trashed issues recoverable
    /// for a grace period.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// client
    ///     .issues()
    ///     .delete(linear_api::IssueRef::identifier("ENG-123"))
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn delete(&self, issue: impl Into<IssueRef>) -> Result<()> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_delete: SuccessPayload,
        }
        let issue = issue.into();
        let data: Data = self
            .client
            .mutation(
                "IssueDelete",
                ISSUE_DELETE,
                serde_json::json!({ "id": issue.api_string() }),
            )
            .await?;
        crate::types::ensure_success("IssueDelete", data.issue_delete.success)
    }

    /// Adds one label to an issue, returning the updated issue. For bulk
    /// label changes prefer [`IssuesService::update`] with
    /// [`IssueUpdateInput::added_label_ids`].
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let label = linear_api::LabelId::new("2f7fb5b1-9d5d-4d70-a806-04f8ad4c3702");
    /// let issue = client
    ///     .issues()
    ///     .add_label(linear_api::IssueRef::identifier("ENG-123"), &label)
    ///     .await?;
    /// println!("{} now has {} labels", issue.identifier, issue.labels.len());
    /// # Ok(()) }
    /// ```
    pub async fn add_label(&self, issue: impl Into<IssueRef>, label: &LabelId) -> Result<Issue> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_add_label: IssuePayload,
        }
        let issue = issue.into();
        let data: Data = self
            .client
            .mutation(
                "IssueAddLabel",
                ISSUE_ADD_LABEL,
                serde_json::json!({ "id": issue.api_string(), "labelId": label.as_str() }),
            )
            .await?;
        payload_issue("IssueAddLabel", data.issue_add_label)
    }

    /// Removes one label from an issue, returning the updated issue. For bulk
    /// label changes prefer [`IssuesService::update`] with
    /// [`IssueUpdateInput::removed_label_ids`].
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let label = linear_api::LabelId::new("2f7fb5b1-9d5d-4d70-a806-04f8ad4c3702");
    /// let issue = client
    ///     .issues()
    ///     .remove_label(linear_api::IssueRef::identifier("ENG-123"), &label)
    ///     .await?;
    /// println!("{} now has {} labels", issue.identifier, issue.labels.len());
    /// # Ok(()) }
    /// ```
    pub async fn remove_label(&self, issue: impl Into<IssueRef>, label: &LabelId) -> Result<Issue> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_remove_label: IssuePayload,
        }
        let issue = issue.into();
        let data: Data = self
            .client
            .mutation(
                "IssueRemoveLabel",
                ISSUE_REMOVE_LABEL,
                serde_json::json!({ "id": issue.api_string(), "labelId": label.as_str() }),
            )
            .await?;
        payload_issue("IssueRemoveLabel", data.issue_remove_label)
    }
}