tod 0.17.0

An unofficial Todoist command-line client
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
use crate::{
    comments::Comment,
    config::Config,
    errors::Error,
    format,
    projects::Project,
    tasks::{self, FormatType, SortOrder, Task, priority::Priority},
    todoist,
};
use futures::{StreamExt, TryStreamExt, future, stream};
use std::collections::HashSet;
use std::fmt::Display;
use tokio::{fs, io::AsyncReadExt, task::JoinError};

#[derive(Clone)]
pub enum Flag {
    Project(Project),
    Filter(String),
}

impl Display for Flag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Flag::Project(project) => write!(f, "{project}"),
            Flag::Filter(filter) => write!(f, "'{filter}'"),
        }
    }
}

/// Get a list of all tasks
pub async fn view(config: &mut Config, flag: Flag, sort: &SortOrder) -> Result<String, Error> {
    let list_of_tasks = match &flag {
        Flag::Project(project) => vec![(
            project.name.clone(),
            todoist::all_tasks_by_project(config, project, None).await?,
        )],
        Flag::Filter(filter) => todoist::all_tasks_by_filters(config, filter).await?,
    };

    let mut buffer = String::new();

    for (query, tasks) in list_of_tasks {
        let title = format!("Tasks for {query}");
        buffer.push('\n');
        buffer.push_str(&format::green_string(&title));
        buffer.push('\n');
        for task in tasks::sort(tasks, config, *sort) {
            let comments = Vec::new();
            let text = task.fmt(comments, config, FormatType::List, true).await?;
            buffer.push('\n');
            buffer.push_str(&text);
        }
    }
    Ok(buffer)
}

pub async fn fetch_tasks_by_flag<F, P>(
    config: &Config,
    flag: &Flag,
    project_filter: P,
    filter_filter: F,
) -> Result<Vec<Task>, Error>
where
    P: Fn(&Task) -> bool,
    F: Fn(&Task) -> bool,
{
    let tasks = match flag {
        Flag::Project(project) => todoist::all_tasks_by_project(config, project, None)
            .await?
            .into_iter()
            .filter(|task| project_filter(task))
            .collect::<Vec<Task>>(),
        Flag::Filter(filter) => todoist::all_tasks_by_filters(config, filter)
            .await?
            .into_iter()
            .flat_map(|(_, tasks)| tasks)
            .filter(|task| filter_filter(task))
            .collect::<Vec<Task>>(),
    };

    Ok(tasks)
}

/// Prioritize all unprioritized tasks
pub async fn prioritize(config: &Config, flag: Flag, sort: &SortOrder) -> Result<String, Error> {
    let project_filter = |task: &Task| task.priority == Priority::None;
    let filter_filter = |_task: &Task| true;
    let tasks = fetch_tasks_by_flag(config, &flag, project_filter, filter_filter).await?;

    let empty_text = format!("No tasks for {flag}");
    let success = format!("Successfully prioritized {flag}");

    if tasks.is_empty() {
        return Ok(format::green_string(&empty_text));
    }

    let tasks = tasks::sort(tasks, config, *sort);

    let handles = stream::iter(tasks)
        .then(|task| async {
            println!();
            tasks::set_priority(config, task, true).await
        })
        .try_collect::<Vec<_>>()
        .await?;
    future::join_all(handles).await;
    Ok(format::green_string(&success))
}

/// Add reminders to all tasks that do not have them
pub async fn remind(config: &Config, flag: Flag, sort: &SortOrder) -> Result<String, Error> {
    let reminder_task_ids = todoist::all_reminders(config, None)
        .await?
        .into_iter()
        .map(|r| r.item_id)
        .collect::<HashSet<String>>();

    let filter = |task: &Task| !reminder_task_ids.contains(&task.id);
    let tasks = fetch_tasks_by_flag(config, &flag, filter, filter).await?;

    if tasks.is_empty() {
        let empty_text = format!("No tasks for {flag}");
        return Ok(format::green_string(&empty_text));
    }

    let tasks = tasks::sort(tasks, config, *sort);

    let handles = stream::iter(tasks)
        .then(|task| async {
            println!();
            tasks::create_reminder(config, task).await
        })
        .try_collect::<Vec<_>>()
        .await?
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();
    future::join_all(handles).await;
    let success = format!("Successfully reminded {flag}");
    Ok(format::green_string(&success))
}

/// Gives tasks durations
pub async fn timebox(config: &Config, flag: Flag, sort: &SortOrder) -> Result<String, Error> {
    let project_filter = |task: &Task| task.duration.is_none();
    let filter_filter = |_task: &Task| true;
    let tasks = fetch_tasks_by_flag(config, &flag, project_filter, filter_filter).await?;

    let empty_text = format!("No tasks for {flag}");
    let success = format!("Successfully timeboxed {flag}");

    if tasks.is_empty() {
        return Ok(format::green_string(&empty_text));
    }

    let tasks = tasks::sort(tasks, config, *sort);
    let mut task_count = i32::try_from(tasks.len())?;
    let mut handles = Vec::new();
    for task in tasks {
        println!();
        match tasks::timebox_task(&config.reload().await?, task, &mut task_count, false).await? {
            Some(handle) => handles.push(handle),
            None => return Ok(format::green_string("Exited")),
        }
    }
    future::join_all(handles).await;
    Ok(format::green_string(&success))
}

/// Get next tasks and give an interactive prompt for completing them one by one
pub async fn process(config: &Config, flag: Flag, sort: &SortOrder) -> Result<String, Error> {
    let project_filter = |task: &Task| {
        task.is_today(config).unwrap_or_default()
            || task.has_no_date()
            || task.is_overdue(config).unwrap_or_default()
    };
    let filter_filter = |_task: &Task| true;
    let tasks = fetch_tasks_by_flag(config, &flag, project_filter, filter_filter).await?;

    let with_project = match &flag {
        Flag::Project(..) => false,
        Flag::Filter(..) => true,
    };
    let tasks = tasks::reject_parent_tasks(tasks, config).await;

    let empty_text = format!("No tasks for {flag}");
    let success = format!("Successfully processed {flag}");

    if tasks.is_empty() {
        return Ok(format::green_string(&empty_text));
    }

    let tasks = tasks::sort(tasks, config, *sort);
    let mut task_count = i32::try_from(tasks.len())?;
    let tasks_with_comments = fetch_comments_for_tasks(tasks, config).await;
    let mut handles = Vec::new();
    for task_with_comments in tasks_with_comments {
        match process_task_with_comments(task_with_comments, config, &mut task_count, with_project)
            .await?
        {
            ProcessTaskOutcome::Handle(handle) => handles.push(handle),
            ProcessTaskOutcome::Exit => return Ok(format::green_string("Exited")),
            ProcessTaskOutcome::Skip => {}
        }
    }
    future::join_all(handles).await;
    Ok(format::green_string(&success))
}

enum ProcessTaskOutcome {
    Handle(tokio::task::JoinHandle<()>),
    Exit,
    Skip,
}

async fn process_task_with_comments(
    task_with_comments: Result<(Task, Result<Vec<Comment>, Error>), JoinError>,
    config: &Config,
    task_count: &mut i32,
    with_project: bool,
) -> Result<ProcessTaskOutcome, Error> {
    let (task, comments, with_project) = match task_with_comments {
        Ok((task, Ok(comments))) => (task, comments, with_project),
        Ok((task, Err(Error { message, source }))) => {
            println!("Could not fetch comments from {source}: {message}");
            (task, Vec::new(), false)
        }
        Err(JoinError { .. }) => {
            println!("JoinError");
            return Ok(ProcessTaskOutcome::Skip);
        }
    };

    println!();
    match tasks::process_task(
        comments,
        &config.reload().await?,
        task,
        task_count,
        with_project,
    )
    .await?
    {
        Some(handle) => Ok(ProcessTaskOutcome::Handle(handle)),
        None => Ok(ProcessTaskOutcome::Exit),
    }
}

async fn fetch_comments_for_tasks(
    tasks: Vec<Task>,
    config: &Config,
) -> Vec<Result<(Task, Result<Vec<Comment>, Error>), JoinError>> {
    let handles = tasks
        .into_iter()
        .map(|task| {
            let config = config.clone();
            tokio::spawn(async move {
                let comments = todoist::all_comments(&config, &task.id, None).await;
                (task, comments)
            })
        })
        .collect::<Vec<_>>();
    future::join_all(handles).await
}

/// Puts labels on tasks
pub async fn label(
    config: &Config,
    flag: Flag,
    labels: &[String],
    sort: &SortOrder,
) -> Result<String, Error> {
    let filter = |_task: &Task| true;
    let tasks = fetch_tasks_by_flag(config, &flag, filter, filter).await?;

    let empty_text = format!("No tasks for {flag}");
    let success = format!("Successfully labeled {flag}");

    if tasks.is_empty() {
        return Ok(format::green_string(&empty_text));
    }

    let tasks = tasks::sort(tasks, config, *sort);
    let handles = stream::iter(tasks)
        .then(|task| async {
            println!();
            tasks::label_task(config, task, labels).await
        })
        .try_collect::<Vec<_>>()
        .await?;
    future::join_all(handles).await;
    Ok(format::green_string(&success))
}

pub async fn import(config: &Config, file_path: &str) -> Result<String, Error> {
    let mut lines = String::new();
    fs::File::open(file_path)
        .await?
        .read_to_string(&mut lines)
        .await?;

    let lines: Vec<String> = lines
        .split('\n')
        .map(std::borrow::ToOwned::to_owned)
        .filter(|s| !s.is_empty())
        .collect();
    for line in lines {
        todoist::quick_create_task(config, &line, None).await?;
    }

    Ok("✓".into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test;
    use crate::test::responses::ResponseFromFile;
    use pretty_assertions::assert_eq;

    #[tokio::test]
    // Test importing the import_tasks.txt file creates 14 tasks
    /// This file is used to test the import functionality
    async fn test_import_creates_14_tasks() {
        let mut server = mockito::Server::new_async().await;
        // File to import and quantity specified here - expects 14 items
        let import_file = "tests/inputs/import_tasks.txt";
        let import_qty = 14;

        // Expect 14 POSTs to /api/v1/tasks/quick
        let mock = server
            .mock("POST", "/api/v1/tasks/quick")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTask.read().await)
            .expect(import_qty)
            .create_async()
            .await;

        let config = test::fixtures::config().await.with_mock_url(server.url());

        assert_eq!(import(&config, import_file).await, Ok(String::from("✓")));

        mock.assert();
    }

    #[tokio::test]
    async fn test_prioritize() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;
        let mock2 = server
            .mock("POST", "/api/v1/tasks/6Xqhv4cwxgjwG9w8")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(1);

        let filter = String::from("today");
        let sort = &SortOrder::Value;
        let result = prioritize(&config, Flag::Filter(filter), sort).await;
        assert_eq!(result, Ok(String::from("Successfully prioritized 'today'")));
        mock.assert();
        mock2.assert();
    }
    #[tokio::test]
    async fn test_timebox() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasksWithoutDuration.read().await)
            .create_async()
            .await;

        let mock2 = server
            .mock("POST", "/api/v1/tasks/999999")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTask.read().await)
            .create_async()
            .await;

        let mock4 = server
            .mock(
                "GET",
                "/api/v1/comments/?task_id=6Xqhv4cwxgjwG9w8&limit=200",
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::CommentsAllTypes.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(1)
            .with_mock_string("tod")
            .create()
            .await
            .expect("expected value or result, got None or Err");

        let binding = config
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .to_owned();
        let sort = &SortOrder::Value;
        let result = timebox(&config, Flag::Project(project), sort).await;
        assert_matches!(result, Ok(x) if x.contains("Successfully timeboxed"));

        let config = config.mock_select(2);

        let binding = config
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .to_owned();
        let result = timebox(&config, Flag::Project(project), sort).await;
        assert_matches!(result, Ok(x) if x.contains("Successfully timeboxed"));

        let config = config.mock_select(3);

        let binding = config
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .to_owned();
        let result = timebox(&config, Flag::Project(project.clone()), sort).await;
        assert_matches!(result, Ok(x) if x.contains("Successfully timeboxed"));

        let result = timebox(&config, Flag::Project(project), sort).await;
        assert_matches!(result, Ok(x) if x.contains("Successfully timeboxed"));
        mock.expect(2);
        mock2.expect(2);
        mock4.expect(1);
    }

    #[tokio::test]
    async fn test_timebox_returns_exited_when_quit_is_selected() {
        let mut server = mockito::Server::new_async().await;
        let tasks_mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasksWithoutDuration.read().await)
            .create_async()
            .await;
        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(4)
            .create()
            .await
            .expect("config should be created");

        let result = timebox(
            &config,
            Flag::Filter("today".to_string()),
            &SortOrder::Value,
        )
        .await;

        assert_eq!(result, Ok("Exited".to_string()));
        tasks_mock.assert();
    }

    #[tokio::test]
    async fn test_prioritize_tasks_with_no_tasks() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config().await.with_mock_url(server.url());

        let binding = config
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .to_owned();
        let sort = &SortOrder::Value;

        let result = prioritize(&config, Flag::Project(project), sort).await;
        assert_eq!(
            result,
            Ok(String::from(
                "No tasks for myproject\nhttps://app.todoist.com/app/project/123"
            ))
        );
        mock.assert();
    }

    #[tokio::test]
    async fn test_empty_task_lists_return_messages() {
        let mut server = mockito::Server::new_async().await;
        let reminders_mock = server
            .mock("GET", "/api/v1/reminders?limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"results":[],"next_cursor":null}"#)
            .create_async()
            .await;
        let tasks_mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"results":[],"next_cursor":null}"#)
            .expect(3)
            .create_async()
            .await;
        let config = test::fixtures::config().await.with_mock_url(server.url());

        assert_eq!(
            remind(
                &config,
                Flag::Filter("today".to_string()),
                &SortOrder::Value,
            )
            .await,
            Ok("No tasks for 'today'".to_string())
        );
        assert_eq!(
            timebox(
                &config,
                Flag::Filter("today".to_string()),
                &SortOrder::Value,
            )
            .await,
            Ok("No tasks for 'today'".to_string())
        );
        assert_eq!(
            process(
                &config,
                Flag::Filter("today".to_string()),
                &SortOrder::Value,
            )
            .await,
            Ok("No tasks for 'today'".to_string())
        );
        reminders_mock.assert();
        tasks_mock.assert();
    }
    #[tokio::test]
    async fn test_process_with_filter() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let mock2 = server
            .mock("POST", "/api/v1/tasks/6Xqhv4cwxgjwG9w8/close")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTask.read().await)
            .create_async()
            .await;

        let mock3 = server
            .mock(
                "GET",
                "/api/v1/comments/?task_id=6Xqhv4cwxgjwG9w8&limit=200",
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::CommentsAllTypes.read().await)
            .create_async()
            .await;
        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(0)
            .create()
            .await
            .expect("expected value or result, got None or Err");
        let filter = String::from("today");
        let sort = &SortOrder::Value;

        let result = process(&config, Flag::Filter(filter), sort).await;
        assert_eq!(result, Ok("Successfully processed 'today'".to_string()));
        mock.assert();
        mock2.assert();
        mock3.assert();
    }

    #[tokio::test]
    async fn test_process_with_project() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let mock2 = server
            .mock("POST", "/api/v1/tasks/6Xqhv4cwxgjwG9w8/close")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTask.read().await)
            .create_async()
            .await;

        let mock3 = server
            .mock(
                "GET",
                "/api/v1/comments/?task_id=6Xqhv4cwxgjwG9w8&limit=200",
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::CommentsAllTypes.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(0)
            .create()
            .await
            .expect("expected value or result, got None or Err");

        let binding = config
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .to_owned();
        let sort = &SortOrder::Value;

        let result = process(&config, Flag::Project(project), sort).await;
        assert_eq!(
            result,
            Ok(
                "Successfully processed myproject\nhttps://app.todoist.com/app/project/123"
                    .to_string()
            )
        );
        mock.assert();
        mock2.assert();
        mock3.assert();
    }

    #[tokio::test]
    async fn test_process_returns_exited_when_quit_is_selected() {
        let mut server = mockito::Server::new_async().await;
        let tasks_mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;
        let comments_mock = server
            .mock(
                "GET",
                "/api/v1/comments/?task_id=6Xqhv4cwxgjwG9w8&limit=200",
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::CommentsAllTypes.read().await)
            .create_async()
            .await;
        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(6)
            .create()
            .await
            .expect("config should be created");

        let result = process(
            &config,
            Flag::Filter("today".to_string()),
            &SortOrder::Value,
        )
        .await;

        assert_eq!(result, Ok("Exited".to_string()));
        tasks_mock.assert();
        comments_mock.assert();
    }

    #[tokio::test]
    async fn test_process_handles_comment_fetch_errors() {
        let mut server = mockito::Server::new_async().await;
        let tasks_mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .expect(2)
            .create_async()
            .await;
        let comments_mock = server
            .mock(
                "GET",
                "/api/v1/comments/?task_id=6Xqhv4cwxgjwG9w8&limit=200",
            )
            .with_status(500)
            .with_body("comment request failed")
            .expect(2)
            .create_async()
            .await;
        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(1)
            .create()
            .await
            .expect("config should be created");

        let skipped = process(
            &config,
            Flag::Filter("today".to_string()),
            &SortOrder::Value,
        )
        .await;
        assert_eq!(skipped, Ok("Successfully processed 'today'".to_string()));

        let quit_config = config
            .mock_select(6)
            .create()
            .await
            .expect("quit config should be created");
        let exited = process(
            &quit_config,
            Flag::Filter("today".to_string()),
            &SortOrder::Value,
        )
        .await;
        assert_eq!(exited, Ok("Exited".to_string()));
        tasks_mock.assert();
        comments_mock.assert();
    }

    #[tokio::test]
    async fn test_process_skips_cancelled_comment_fetch() {
        let handle: tokio::task::JoinHandle<(Task, Result<Vec<Comment>, Error>)> =
            tokio::spawn(std::future::pending());
        handle.abort();
        let cancelled = handle.await;
        let config = test::fixtures::config().await;
        let mut task_count = 1;

        let outcome = process_task_with_comments(cancelled, &config, &mut task_count, false)
            .await
            .expect("cancelled comment fetch should be skipped");

        assert!(matches!(outcome, ProcessTaskOutcome::Skip));
    }
    #[tokio::test]
    async fn test_label() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let mock2 = server
            .mock("POST", "/api/v1/tasks/6Xqhv4cwxgjwG9w8")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config().await.with_mock_url(server.url());

        let config_dir = dirs::config_dir().expect("Could not find config directory");

        let config_with_timezone = config
            .with_timezone("US/Pacific")
            .with_path(config_dir.join("test3"))
            .with_mock_url(server.url())
            .mock_select(0);

        config_with_timezone
            .clone()
            .create()
            .await
            .expect("expected value or result, got None or Err");

        let filter = String::from("today");
        let labels = vec![String::from("thing")];
        let sort = &SortOrder::Value;

        assert_eq!(
            label(&config_with_timezone, Flag::Filter(filter), &labels, sort).await,
            Ok(String::from("Successfully labeled 'today'"))
        );
        mock.assert();
        mock2.assert();
    }

    #[tokio::test]
    async fn test_remind() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/reminders?limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"results":[],"next_cursor":null}"#)
            .create_async()
            .await;

        let mock2 = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let mock3 = server
            .mock("POST", "/api/v1/reminders")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{
                    "id": "abc",
                    "item_id": "6Xqhv4cwxgjwG9w8",
                    "notify_uid": "635166",
                    "type": "relative",
                    "is_deleted": false,
                    "minute_offset": 0,
                    "is_urgent": false,
                    "due": {
                        "date": "2026-01-18T17:00:00",
                        "timezone": null,
                        "string": "2026-01-18 17:00",
                        "lang": "en",
                        "is_recurring": false
                    }
                }"#,
            )
            .create_async()
            .await;

        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .with_mock_string("tomorrow");

        let filter = String::from("today");
        let sort = &SortOrder::Value;

        let result = remind(&config, Flag::Filter(filter), sort).await;
        assert_eq!(result, Ok(String::from("Successfully reminded 'today'")));
        mock.assert();
        mock2.assert();
        mock3.assert();
    }

    #[tokio::test]
    async fn test_remind_with_project() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/reminders?limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"results":[],"next_cursor":null}"#)
            .create_async()
            .await;

        let mock2 = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let mock3 = server
            .mock("POST", "/api/v1/reminders")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{
                    "id": "abc",
                    "item_id": "6Xqhv4cwxgjwG9w8",
                    "notify_uid": "635166",
                    "type": "relative",
                    "is_deleted": false,
                    "minute_offset": 0,
                    "is_urgent": false,
                    "due": {
                        "date": "2026-01-18T17:00:00",
                        "timezone": null,
                        "string": "2026-01-18 17:00",
                        "lang": "en",
                        "is_recurring": false
                    }
                }"#,
            )
            .create_async()
            .await;

        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .with_mock_string("tomorrow");

        let binding = config
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .to_owned();
        let sort = &SortOrder::Value;

        let result = remind(&config, Flag::Project(project), sort).await;
        assert_eq!(
            result,
            Ok(String::from(
                "Successfully reminded myproject\nhttps://app.todoist.com/app/project/123"
            ))
        );
        mock.assert();
        mock2.assert();
        mock3.assert();
    }
    #[tokio::test]
    async fn test_remind_with_project_completes_task() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/reminders?limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"results":[],"next_cursor":null}"#)
            .create_async()
            .await;

        let mock2 = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let mock3 = server
            .mock("POST", "/api/v1/tasks/6Xqhv4cwxgjwG9w8/close")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTask.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .with_mock_string("complete");

        let binding = config
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .to_owned();
        let sort = &SortOrder::Value;

        let result = remind(&config, Flag::Project(project), sort).await;
        assert_eq!(
            result,
            Ok(String::from(
                "Successfully reminded myproject\nhttps://app.todoist.com/app/project/123"
            ))
        );
        mock.assert();
        mock2.assert();
        mock3.assert();
    }

    #[tokio::test]
    async fn test_view() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/filter?query=today&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config().await.with_mock_url(server.url());

        let mut config_with_timezone = config
            .with_timezone("US/Pacific")
            .with_mock_url(server.url());
        let filter = String::from("today");
        let sort = &SortOrder::Value;

        let tasks = view(&mut config_with_timezone, Flag::Filter(filter), sort)
            .await
            .expect("expected value or result, got None or Err");

        assert!(tasks.contains("Tasks for today"));
        mock.assert();
    }

    #[tokio::test]
    async fn test_view_with_project() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let config = test::fixtures::config().await.with_mock_url(server.url());

        let mut config_with_timezone = config
            .with_timezone("US/Pacific")
            .with_mock_url(server.url());

        let binding = config_with_timezone
            .projects()
            .await
            .expect("Failed to fetch projects asynchronously");
        let project = binding
            .first()
            .expect("Expected at least one project in binding")
            .clone();
        let sort = &SortOrder::Value;

        let tasks = view(&mut config_with_timezone, Flag::Project(project), sort)
            .await
            .expect("expected value or result, got None or Err");

        assert!(tasks.contains("Tasks for"));
        assert!(tasks.contains("- TEST\n"));
        mock.assert();
    }
}