asanaclient 0.1.1

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

use crate::api::portfolios::PortfolioItemExpanded;
use crate::types::requests::{
    AddDependenciesData, AddDependenciesRequest, AddDependentsData, AddDependentsRequest,
    AddFollowersData, AddFollowersRequest, AddProjectData, AddProjectRequest, AddTagData,
    AddTagRequest, CreateCommentData, CreateCommentRequest, CreateTaskData, CreateTaskRequest,
    RemoveDependenciesData, RemoveDependenciesRequest, RemoveDependentsData,
    RemoveDependentsRequest, RemoveFollowersData, RemoveFollowersRequest, RemoveProjectData,
    RemoveProjectRequest, RemoveTagData, RemoveTagRequest, SetParentData, SetParentRequest,
    UpdateTaskData, UpdateTaskRequest,
};
use crate::types::{Story, Task, TaskDependency, TaskRef};
use crate::{Client, Error};

/// Fields to request for a basic task fetch.
pub const TASK_FIELDS: &str = "gid,name,resource_type,completed,completed_at,\
    assignee,assignee.name,due_on,due_at,start_on,notes,created_at,modified_at,\
    permalink_url,parent,num_likes,num_subtasks,liked,projects,projects.name,\
    workspace,tags,memberships,memberships.project,memberships.project.name,\
    memberships.section,memberships.section.name";

/// Fields to request for a full task fetch.
pub const TASK_FULL_FIELDS: &str = "gid,name,resource_type,completed,completed_at,\
    completed_by,completed_by.name,assignee,assignee.name,assignee.email,\
    due_on,due_at,start_on,start_at,notes,html_notes,created_at,created_by,\
    created_by.name,modified_at,permalink_url,parent,parent.name,num_likes,\
    num_subtasks,liked,projects,projects.name,workspace,workspace.name,\
    tags,tags.name,memberships,memberships.project,memberships.project.name,\
    memberships.section,memberships.section.name,assignee_section,\
    assignee_section.name";

/// Fields to request for subtasks.
pub const SUBTASK_FIELDS: &str = "gid,name,completed,assignee,assignee.name,\
    due_on,num_subtasks";

/// Fields to request for recursive task fetching (includes project refs).
pub const RECURSIVE_TASK_FIELDS: &str = "gid,name,resource_type,completed,completed_at,\
    assignee,assignee.name,due_on,due_at,start_on,notes,created_at,modified_at,\
    permalink_url,parent,parent.name,num_likes,num_subtasks,liked,\
    projects,projects.name,workspace,tags,memberships,memberships.project,\
    memberships.project.name,memberships.section,memberships.section.name";

/// Fields to request for stories/comments.
pub const STORY_FIELDS: &str = "gid,created_at,created_by,created_by.name,\
    resource_subtype,text,html_text,is_pinned,is_edited,num_likes,liked";

/// API for task operations.
pub struct TasksApi<'a> {
    client: &'a Client,
}

impl<'a> TasksApi<'a> {
    /// Create a new tasks API instance.
    pub fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Get a task by its GID.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use asanaclient::Client;
    /// # async fn example() -> Result<(), asanaclient::Error> {
    /// let client = Client::from_env()?;
    /// let task = client.tasks().get("12345").await?;
    /// println!("Task: {} (completed: {})", task.name, task.completed);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get(&self, gid: &str) -> Result<Task, Error> {
        let path = format!("/tasks/{}", gid);
        let query = [("opt_fields", TASK_FIELDS)];
        self.client.get(&path, &query).await
    }

    /// Get a task with full details.
    pub async fn get_full(&self, gid: &str) -> Result<Task, Error> {
        let path = format!("/tasks/{}", gid);
        let query = [("opt_fields", TASK_FULL_FIELDS)];
        self.client.get(&path, &query).await
    }

    /// Get subtasks of a task.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use asanaclient::Client;
    /// # async fn example() -> Result<(), asanaclient::Error> {
    /// let client = Client::from_env()?;
    /// let subtasks = client.tasks().subtasks("12345").await?;
    /// for subtask in subtasks {
    ///     println!("  - {} (completed: {})", subtask.name, subtask.completed);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn subtasks(&self, gid: &str) -> Result<Vec<Task>, Error> {
        let path = format!("/tasks/{}/subtasks", gid);
        let query = [("opt_fields", SUBTASK_FIELDS)];
        self.client.get_all(&path, &query).await
    }

    /// Get tasks that this task depends on (blockers).
    pub async fn dependencies(&self, gid: &str) -> Result<Vec<TaskDependency>, Error> {
        let path = format!("/tasks/{}/dependencies", gid);
        let query = [("opt_fields", "gid,name,resource_type")];
        self.client.get_all(&path, &query).await
    }

    /// Get tasks that depend on this task (blocked by this task).
    pub async fn dependents(&self, gid: &str) -> Result<Vec<TaskDependency>, Error> {
        let path = format!("/tasks/{}/dependents", gid);
        let query = [("opt_fields", "gid,name,resource_type")];
        self.client.get_all(&path, &query).await
    }

    /// Get all stories (comments and activity) for a task.
    pub async fn stories(&self, gid: &str) -> Result<Vec<Story>, Error> {
        let path = format!("/tasks/{}/stories", gid);
        let query = [("opt_fields", STORY_FIELDS)];
        self.client.get_all(&path, &query).await
    }

    /// Get only comments for a task (filters out system messages).
    pub async fn comments(&self, gid: &str) -> Result<Vec<Story>, Error> {
        let stories = self.stories(gid).await?;
        Ok(stories.into_iter().filter(|s| s.is_comment()).collect())
    }

    /// Get subtasks with full fields for recursive fetching.
    pub(crate) async fn subtasks_full(&self, gid: &str) -> Result<Vec<Task>, Error> {
        let path = format!("/tasks/{}/subtasks", gid);
        let query = [("opt_fields", RECURSIVE_TASK_FIELDS)];
        self.client.get_all(&path, &query).await
    }

    // ========== Write Operations ==========

    /// Create a new task.
    ///
    /// Either `workspace` or `projects` must be specified in the data.
    pub async fn create(&self, data: CreateTaskData) -> Result<Task, Error> {
        let path = "/tasks".to_string();
        let request = CreateTaskRequest { data };
        self.client.post(&path, &request).await
    }

    /// Create a subtask under a parent task.
    pub async fn create_subtask(
        &self,
        parent_gid: &str,
        data: CreateTaskData,
    ) -> Result<Task, Error> {
        let path = format!("/tasks/{}/subtasks", parent_gid);
        let request = CreateTaskRequest { data };
        self.client.post(&path, &request).await
    }

    /// Update a task.
    pub async fn update(&self, gid: &str, data: UpdateTaskData) -> Result<Task, Error> {
        let path = format!("/tasks/{}", gid);
        let request = UpdateTaskRequest { data };
        self.client.put(&path, &request).await
    }

    /// Delete a task.
    pub async fn delete(&self, gid: &str) -> Result<(), Error> {
        let path = format!("/tasks/{}", gid);
        self.client.delete(&path).await
    }

    /// Add a task to a project.
    pub async fn add_project(
        &self,
        task_gid: &str,
        project_gid: &str,
        section_gid: Option<&str>,
    ) -> Result<(), Error> {
        let path = format!("/tasks/{}/addProject", task_gid);
        let request = AddProjectRequest {
            data: AddProjectData {
                project: project_gid.to_string(),
                section: section_gid.map(String::from),
                insert_before: None,
                insert_after: None,
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Remove a task from a project.
    pub async fn remove_project(&self, task_gid: &str, project_gid: &str) -> Result<(), Error> {
        let path = format!("/tasks/{}/removeProject", task_gid);
        let request = RemoveProjectRequest {
            data: RemoveProjectData {
                project: project_gid.to_string(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Add a tag to a task.
    pub async fn add_tag(&self, task_gid: &str, tag_gid: &str) -> Result<(), Error> {
        let path = format!("/tasks/{}/addTag", task_gid);
        let request = AddTagRequest {
            data: AddTagData {
                tag: tag_gid.to_string(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Remove a tag from a task.
    pub async fn remove_tag(&self, task_gid: &str, tag_gid: &str) -> Result<(), Error> {
        let path = format!("/tasks/{}/removeTag", task_gid);
        let request = RemoveTagRequest {
            data: RemoveTagData {
                tag: tag_gid.to_string(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Set the parent of a task.
    ///
    /// Pass `None` for `parent_gid` to remove the parent (make it a top-level task).
    pub async fn set_parent(
        &self,
        task_gid: &str,
        parent_gid: Option<&str>,
    ) -> Result<Task, Error> {
        let path = format!("/tasks/{}/setParent", task_gid);
        let request = SetParentRequest {
            data: SetParentData {
                parent: parent_gid.map(String::from),
                insert_before: None,
                insert_after: None,
            },
        };
        self.client.post(&path, &request).await
    }

    /// Add dependencies to a task (tasks that must be completed before this one).
    pub async fn add_dependencies(
        &self,
        task_gid: &str,
        dependency_gids: &[&str],
    ) -> Result<(), Error> {
        let path = format!("/tasks/{}/addDependencies", task_gid);
        let request = AddDependenciesRequest {
            data: AddDependenciesData {
                dependencies: dependency_gids.iter().map(|s| s.to_string()).collect(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Remove dependencies from a task.
    pub async fn remove_dependencies(
        &self,
        task_gid: &str,
        dependency_gids: &[&str],
    ) -> Result<(), Error> {
        let path = format!("/tasks/{}/removeDependencies", task_gid);
        let request = RemoveDependenciesRequest {
            data: RemoveDependenciesData {
                dependencies: dependency_gids.iter().map(|s| s.to_string()).collect(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Add dependents to a task (tasks that depend on this one).
    pub async fn add_dependents(
        &self,
        task_gid: &str,
        dependent_gids: &[&str],
    ) -> Result<(), Error> {
        let path = format!("/tasks/{}/addDependents", task_gid);
        let request = AddDependentsRequest {
            data: AddDependentsData {
                dependents: dependent_gids.iter().map(|s| s.to_string()).collect(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Remove dependents from a task.
    pub async fn remove_dependents(
        &self,
        task_gid: &str,
        dependent_gids: &[&str],
    ) -> Result<(), Error> {
        let path = format!("/tasks/{}/removeDependents", task_gid);
        let request = RemoveDependentsRequest {
            data: RemoveDependentsData {
                dependents: dependent_gids.iter().map(|s| s.to_string()).collect(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Add followers to a task.
    pub async fn add_followers(&self, task_gid: &str, follower_gids: &[&str]) -> Result<(), Error> {
        let path = format!("/tasks/{}/addFollowers", task_gid);
        let request = AddFollowersRequest {
            data: AddFollowersData {
                followers: follower_gids.iter().map(|s| s.to_string()).collect(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Remove followers from a task.
    pub async fn remove_followers(
        &self,
        task_gid: &str,
        follower_gids: &[&str],
    ) -> Result<(), Error> {
        let path = format!("/tasks/{}/removeFollowers", task_gid);
        let request = RemoveFollowersRequest {
            data: RemoveFollowersData {
                followers: follower_gids.iter().map(|s| s.to_string()).collect(),
            },
        };
        self.client.post_empty(&path, &request).await
    }

    /// Create a comment on a task.
    pub async fn create_comment(&self, task_gid: &str, text: &str) -> Result<Story, Error> {
        let path = format!("/tasks/{}/stories", task_gid);
        let request = CreateCommentRequest {
            data: CreateCommentData {
                text: Some(text.to_string()),
                html_text: None,
            },
        };
        self.client.post(&path, &request).await
    }

    /// Create a comment with HTML content on a task.
    pub async fn create_comment_html(
        &self,
        task_gid: &str,
        html_text: &str,
    ) -> Result<Story, Error> {
        let path = format!("/tasks/{}/stories", task_gid);
        let request = CreateCommentRequest {
            data: CreateCommentData {
                text: None,
                html_text: Some(html_text.to_string()),
            },
        };
        self.client.post(&path, &request).await
    }

    /// Get all tasks recursively from a project or portfolio.
    ///
    /// This function auto-detects whether the GID refers to a project or portfolio:
    /// - If a project: returns all tasks in that project
    /// - If a portfolio: returns all tasks from all projects in the portfolio
    ///   (including nested portfolios up to `portfolio_depth`)
    ///
    /// The `subtask_depth` parameter controls subtask expansion:
    /// - `None` - Unlimited depth (fetch all nested subtasks)
    /// - `Some(0)` - No subtasks (top-level tasks only)
    /// - `Some(n)` - Fetch n levels of subtasks
    ///
    /// The `portfolio_depth` parameter controls how deep to search for projects
    /// (only applies when GID is a portfolio):
    /// - `None` - Unlimited depth
    /// - `Some(0)` - Only direct child projects (not nested portfolios)
    /// - `Some(n)` - Search n levels of nested portfolios
    ///
    /// Returns a flat `Vec<Task>`. Each task includes ALL projects it belongs to
    /// (not just the ones in the queried hierarchy). Use the `parent` field to
    /// reconstruct task hierarchy if needed.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use asanaclient::Client;
    /// # async fn example() -> Result<(), asanaclient::Error> {
    /// let client = Client::from_env()?;
    ///
    /// // Get all tasks from a project (no subtasks)
    /// let tasks = client.tasks().recursive("project_gid", Some(0), None).await?;
    ///
    /// // Get all tasks from a portfolio with unlimited subtask depth
    /// let tasks = client.tasks().recursive("portfolio_gid", None, None).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn recursive(
        &self,
        gid: &str,
        subtask_depth: Option<usize>,
        portfolio_depth: Option<usize>,
    ) -> Result<Vec<Task>, Error> {
        // Try to detect resource type by attempting to fetch as project first
        match self.client.projects().get(gid).await {
            Ok(_) => {
                // It's a project, get tasks from it
                self.tasks_from_project(gid, subtask_depth).await
            }
            Err(Error::NotFound(_)) => {
                // Not a project, try as portfolio
                self.tasks_from_portfolio(gid, subtask_depth, portfolio_depth)
                    .await
            }
            Err(e) => Err(e),
        }
    }

    /// Get tasks from a single project with optional subtask expansion.
    async fn tasks_from_project(
        &self,
        project_gid: &str,
        subtask_depth: Option<usize>,
    ) -> Result<Vec<Task>, Error> {
        let tasks = self.client.projects().tasks_full(project_gid).await?;
        self.expand_subtasks_flat(tasks, subtask_depth, 0).await
    }

    /// Get tasks from all projects in a portfolio (recursively).
    async fn tasks_from_portfolio(
        &self,
        portfolio_gid: &str,
        subtask_depth: Option<usize>,
        portfolio_depth: Option<usize>,
    ) -> Result<Vec<Task>, Error> {
        let portfolio = self
            .client
            .portfolios()
            .recursive(portfolio_gid, portfolio_depth)
            .await?;
        let project_gids = Self::collect_project_gids_from_portfolio(&portfolio);

        let mut all_tasks = Vec::new();
        for project_gid in project_gids {
            match self.tasks_from_project(&project_gid, subtask_depth).await {
                Ok(tasks) => all_tasks.extend(tasks),
                Err(Error::NotFound(_)) => continue, // Project may have been deleted
                Err(e) => return Err(e),
            }
        }
        Ok(all_tasks)
    }

    /// Collect all project GIDs from a portfolio structure.
    fn collect_project_gids_from_portfolio(
        portfolio: &crate::api::portfolios::PortfolioWithItems,
    ) -> Vec<String> {
        let mut gids = Vec::new();
        for item in &portfolio.items {
            match item {
                PortfolioItemExpanded::Project(p) => gids.push(p.gid.clone()),
                PortfolioItemExpanded::Portfolio(nested) => {
                    gids.extend(Self::collect_project_gids_from_portfolio(nested));
                }
            }
        }
        gids
    }

    /// Expand subtasks into a flat list.
    fn expand_subtasks_flat<'b>(
        &'b self,
        tasks: Vec<Task>,
        subtask_depth: Option<usize>,
        current_depth: usize,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<Task>, Error>> + Send + 'b>>
    {
        Box::pin(async move {
            // Check if we should fetch subtasks at this depth
            let should_fetch_subtasks = match subtask_depth {
                None => true,
                Some(max) => current_depth < max,
            };

            let mut all_tasks = Vec::new();

            for task in tasks {
                let has_subtasks = task.num_subtasks > 0;
                all_tasks.push(task.clone());

                if should_fetch_subtasks && has_subtasks {
                    let subtasks = self.subtasks_full(&task.gid).await?;
                    let expanded = self
                        .expand_subtasks_flat(subtasks, subtask_depth, current_depth + 1)
                        .await?;
                    all_tasks.extend(expanded);
                }
            }

            Ok(all_tasks)
        })
    }

    /// Get a task with full context including subtasks, dependencies, and comments.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use asanaclient::Client;
    /// # use asanaclient::api::tasks::TaskContextOptions;
    /// # async fn example() -> Result<(), asanaclient::Error> {
    /// let client = Client::from_env()?;
    ///
    /// // Get task with subtasks and comments
    /// let ctx = client.tasks().with_context(
    ///     "task123",
    ///     TaskContextOptions::new().with_subtasks().with_comments()
    /// ).await?;
    ///
    /// // Get task with all context
    /// let ctx = client.tasks().with_context(
    ///     "task123",
    ///     TaskContextOptions::new().all()
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn with_context(
        &self,
        gid: &str,
        options: TaskContextOptions,
    ) -> Result<TaskWithContext, Error> {
        let task = self.get_full(gid).await?;

        let subtasks = if options.include_subtasks {
            self.subtasks(gid)
                .await?
                .into_iter()
                .map(|t| TaskRef {
                    gid: t.gid,
                    name: Some(t.name),
                    resource_type: t.resource_type,
                })
                .collect()
        } else {
            Vec::new()
        };

        let (dependencies, dependents) = if options.include_dependencies {
            let deps = self.dependencies(gid).await?;
            let depts = self.dependents(gid).await?;
            (deps, depts)
        } else {
            (Vec::new(), Vec::new())
        };

        let comments = if options.include_comments {
            self.comments(gid).await?
        } else {
            Vec::new()
        };

        Ok(TaskWithContext {
            task,
            subtasks,
            dependencies,
            dependents,
            comments,
        })
    }
}

/// A task with its related data expanded.
#[derive(Debug, Clone, serde::Serialize)]
pub struct TaskWithContext {
    /// The task details.
    #[serde(flatten)]
    pub task: Task,
    /// Subtasks of this task.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub subtasks: Vec<TaskRef>,
    /// Tasks this task depends on (blockers).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub dependencies: Vec<TaskDependency>,
    /// Tasks that depend on this task.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub dependents: Vec<TaskDependency>,
    /// Comments on this task.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub comments: Vec<Story>,
}

/// Options for what context to include when fetching a task.
#[derive(Debug, Clone, Default)]
pub struct TaskContextOptions {
    /// Whether to include subtasks.
    pub include_subtasks: bool,
    /// Whether to include dependencies and dependents.
    pub include_dependencies: bool,
    /// Whether to include comments.
    pub include_comments: bool,
}

impl TaskContextOptions {
    /// Create new options with nothing included.
    pub fn new() -> Self {
        Self::default()
    }

    /// Include subtasks in the response.
    pub fn with_subtasks(mut self) -> Self {
        self.include_subtasks = true;
        self
    }

    /// Include dependencies and dependents in the response.
    pub fn with_dependencies(mut self) -> Self {
        self.include_dependencies = true;
        self
    }

    /// Include comments in the response.
    pub fn with_comments(mut self) -> Self {
        self.include_comments = true;
        self
    }

    /// Include all context (subtasks, dependencies, and comments).
    pub fn all(mut self) -> Self {
        self.include_subtasks = true;
        self.include_dependencies = true;
        self.include_comments = true;
        self
    }
}

impl Client {
    /// Access the tasks API.
    pub fn tasks(&self) -> TasksApi<'_> {
        TasksApi::new(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::requests::{CreateTaskData, UpdateTaskData};
    use wiremock::matchers::{body_json, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn test_client(server: &MockServer) -> Client {
        Client::new("test-token")
            .unwrap()
            .with_base_url(&server.uri())
    }

    #[tokio::test]
    async fn test_create_task() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks"))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "data": {
                    "gid": "newtask",
                    "name": "New Task",
                    "completed": false
                }
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let task = client
            .tasks()
            .create(CreateTaskData {
                name: Some("New Task".to_string()),
                workspace: Some("ws123".to_string()),
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(task.gid, "newtask");
        assert_eq!(task.name, "New Task");
    }

    #[tokio::test]
    async fn test_create_subtask() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/parent123/subtasks"))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "data": {
                    "gid": "subtask1",
                    "name": "Subtask",
                    "completed": false
                }
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let task = client
            .tasks()
            .create_subtask(
                "parent123",
                CreateTaskData {
                    name: Some("Subtask".to_string()),
                    ..Default::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(task.gid, "subtask1");
        assert_eq!(task.name, "Subtask");
    }

    #[tokio::test]
    async fn test_update_task() {
        let server = MockServer::start().await;

        Mock::given(method("PUT"))
            .and(path("/tasks/task123"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {
                    "gid": "task123",
                    "name": "Updated Task",
                    "completed": true
                }
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let task = client
            .tasks()
            .update(
                "task123",
                UpdateTaskData {
                    name: Some("Updated Task".to_string()),
                    completed: Some(true),
                    ..Default::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(task.name, "Updated Task");
        assert!(task.completed);
    }

    #[tokio::test]
    async fn test_add_project() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/addProject"))
            .and(body_json(serde_json::json!({
                "data": {
                    "project": "proj456",
                    "section": "sect789"
                }
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client
            .tasks()
            .add_project("task123", "proj456", Some("sect789"))
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_remove_project() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/removeProject"))
            .and(body_json(serde_json::json!({
                "data": {"project": "proj456"}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.tasks().remove_project("task123", "proj456").await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_add_tag() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/addTag"))
            .and(body_json(serde_json::json!({
                "data": {"tag": "tag456"}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.tasks().add_tag("task123", "tag456").await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_set_parent() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/setParent"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {
                    "gid": "task123",
                    "name": "Task",
                    "completed": false
                }
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let task = client
            .tasks()
            .set_parent("task123", Some("parent456"))
            .await
            .unwrap();

        assert_eq!(task.gid, "task123");
    }

    #[tokio::test]
    async fn test_add_dependencies() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/addDependencies"))
            .and(body_json(serde_json::json!({
                "data": {"dependencies": ["dep1", "dep2"]}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client
            .tasks()
            .add_dependencies("task123", &["dep1", "dep2"])
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_add_followers() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/addFollowers"))
            .and(body_json(serde_json::json!({
                "data": {"followers": ["user1", "user2"]}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client
            .tasks()
            .add_followers("task123", &["user1", "user2"])
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_create_comment() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/stories"))
            .and(body_json(serde_json::json!({
                "data": {"text": "This is a comment"}
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "data": {
                    "gid": "story123",
                    "text": "This is a comment",
                    "resource_subtype": "comment_added"
                }
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let story = client
            .tasks()
            .create_comment("task123", "This is a comment")
            .await
            .unwrap();

        assert_eq!(story.gid, "story123");
        assert_eq!(story.text, Some("This is a comment".to_string()));
    }

    #[tokio::test]
    async fn test_delete_task() {
        let server = MockServer::start().await;

        Mock::given(method("DELETE"))
            .and(path("/tasks/task123"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.tasks().delete("task123").await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_remove_tag() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/removeTag"))
            .and(body_json(serde_json::json!({
                "data": {"tag": "tag456"}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client.tasks().remove_tag("task123", "tag456").await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_remove_dependencies() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/removeDependencies"))
            .and(body_json(serde_json::json!({
                "data": {"dependencies": ["dep1", "dep2"]}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client
            .tasks()
            .remove_dependencies("task123", &["dep1", "dep2"])
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_add_dependents() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/addDependents"))
            .and(body_json(serde_json::json!({
                "data": {"dependents": ["dep1", "dep2"]}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client
            .tasks()
            .add_dependents("task123", &["dep1", "dep2"])
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_remove_dependents() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/removeDependents"))
            .and(body_json(serde_json::json!({
                "data": {"dependents": ["dep1", "dep2"]}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client
            .tasks()
            .remove_dependents("task123", &["dep1", "dep2"])
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_remove_followers() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/removeFollowers"))
            .and(body_json(serde_json::json!({
                "data": {"followers": ["user1", "user2"]}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": {}
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let result = client
            .tasks()
            .remove_followers("task123", &["user1", "user2"])
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_create_comment_html() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/tasks/task123/stories"))
            .and(body_json(serde_json::json!({
                "data": {"html_text": "<body>HTML comment</body>"}
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "data": {
                    "gid": "story123",
                    "html_text": "<body>HTML comment</body>",
                    "resource_subtype": "comment_added"
                }
            })))
            .mount(&server)
            .await;

        let client = test_client(&server);
        let story = client
            .tasks()
            .create_comment_html("task123", "<body>HTML comment</body>")
            .await
            .unwrap();

        assert_eq!(story.gid, "story123");
        assert_eq!(
            story.html_text,
            Some("<body>HTML comment</body>".to_string())
        );
    }
}