tgltrk 0.1.2

Unofficial Toggl Track CLI — manage timers, entries, projects, clients, and tags from the command line
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
use base64::{Engine as _, engine::general_purpose};
use chrono::{DateTime, Utc};
use reqwest::{RequestBuilder, header};
use serde::Serialize;
use serde::de::DeserializeOwned;

use std::time::Duration;

use crate::constants::{API_BASE_URL, API_TIMEOUT_SECS};
use crate::error::{AppError, Result};
use crate::models::{
    ClientId, Project, ProjectId, Tag, TagId, TaskId, TimeEntry, TimeEntryId, User, WorkspaceId,
};

use super::wire::{
    CreateClientRequest, CreateProjectRequest, CreateTagRequest, CreateTimeEntryRequest,
    UpdateClientRequest, UpdateProjectRequest, UpdateTagRequest, UpdateTimeEntryRequest,
    WireClient, WireProject, WireTag, WireTimeEntry, WireUser, WireWorkspace,
};

#[cfg(test)]
use mockall::automock;

// --- Param types ---

pub struct CreateTimeEntryParams {
    pub description: Option<String>,
    pub project_id: Option<ProjectId>,
    pub task_id: Option<TaskId>,
    pub tags: Vec<String>,
    pub billable: bool,
    pub start: Option<DateTime<Utc>>,
    pub stop: Option<DateTime<Utc>>,
    pub duration: Option<i64>,
}

impl From<&TimeEntry> for CreateTimeEntryParams {
    fn from(entry: &TimeEntry) -> Self {
        Self {
            description: entry.description.clone(),
            project_id: entry.project_id,
            task_id: entry.task_id,
            tags: entry.tags.clone(),
            billable: entry.billable,
            start: None,
            stop: None,
            duration: None,
        }
    }
}

pub struct UpdateTimeEntryParams {
    pub description: Option<String>,
    pub project_id: Option<ProjectId>,
    pub tags: Option<Vec<String>>,
    pub billable: Option<bool>,
    pub start: Option<DateTime<Utc>>,
    pub stop: Option<DateTime<Utc>>,
    pub duration: Option<i64>,
}

pub struct CreateProjectParams {
    pub name: String,
    pub client_id: Option<i64>,
}

pub struct UpdateProjectParams {
    pub name: Option<String>,
    pub client_id: Option<i64>,
}

#[cfg_attr(test, automock)]
pub trait ApiClient {
    async fn get_me(&self) -> Result<User>;
    async fn get_current_timer(&self) -> Result<Option<TimeEntry>>;
    async fn get_time_entries(
        &self,
        since: Option<String>,
        until: Option<String>,
    ) -> Result<Vec<TimeEntry>>;
    async fn get_time_entry(&self, entry_id: TimeEntryId) -> Result<TimeEntry>;
    async fn create_time_entry(
        &self,
        workspace_id: WorkspaceId,
        params: &CreateTimeEntryParams,
    ) -> Result<TimeEntry>;
    async fn update_time_entry(
        &self,
        workspace_id: WorkspaceId,
        entry_id: TimeEntryId,
        params: &UpdateTimeEntryParams,
    ) -> Result<TimeEntry>;
    async fn delete_time_entry(
        &self,
        workspace_id: WorkspaceId,
        entry_id: TimeEntryId,
    ) -> Result<()>;
    async fn stop_time_entry(
        &self,
        workspace_id: WorkspaceId,
        entry_id: TimeEntryId,
    ) -> Result<TimeEntry>;
    async fn list_projects(&self, workspace_id: WorkspaceId) -> Result<Vec<Project>>;
    async fn get_project(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
    ) -> Result<Project>;
    async fn create_project(
        &self,
        workspace_id: WorkspaceId,
        params: &CreateProjectParams,
    ) -> Result<Project>;
    async fn update_project(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        params: &UpdateProjectParams,
    ) -> Result<Project>;
    async fn delete_project(&self, workspace_id: WorkspaceId, project_id: ProjectId) -> Result<()>;
    async fn list_tags(&self, workspace_id: WorkspaceId) -> Result<Vec<Tag>>;
    async fn create_tag(&self, workspace_id: WorkspaceId, name: &str) -> Result<Tag>;
    async fn update_tag(&self, workspace_id: WorkspaceId, tag_id: TagId, name: &str)
    -> Result<Tag>;
    async fn delete_tag(&self, workspace_id: WorkspaceId, tag_id: TagId) -> Result<()>;
    async fn list_clients(&self, workspace_id: WorkspaceId) -> Result<Vec<crate::models::Client>>;
    async fn create_client(
        &self,
        workspace_id: WorkspaceId,
        name: &str,
    ) -> Result<crate::models::Client>;
    async fn update_client(
        &self,
        workspace_id: WorkspaceId,
        client_id: ClientId,
        name: &str,
    ) -> Result<crate::models::Client>;
    async fn delete_client(&self, workspace_id: WorkspaceId, client_id: ClientId) -> Result<()>;
    async fn get_client(
        &self,
        workspace_id: WorkspaceId,
        client_id: ClientId,
    ) -> Result<crate::models::Client>;
    async fn list_workspaces(&self) -> Result<Vec<crate::models::Workspace>>;
    async fn get_workspace(&self, workspace_id: WorkspaceId) -> Result<crate::models::Workspace>;
}

pub struct TogglClient {
    http: reqwest::Client,
    base_url: String,
}

impl TogglClient {
    fn build(api_token: &str, base_url: String) -> Result<Self> {
        let auth = format!("{api_token}:api_token");
        let encoded = general_purpose::STANDARD.encode(auth);
        let header_value = header::HeaderValue::from_str(&format!("Basic {encoded}"))
            .map_err(|e| AppError::Auth(format!("Invalid token: {e}")))?;

        let mut headers = header::HeaderMap::new();
        headers.insert(header::AUTHORIZATION, header_value);
        headers.insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("application/json"),
        );

        let http = reqwest::Client::builder()
            .default_headers(headers)
            .timeout(Duration::from_secs(API_TIMEOUT_SECS))
            .user_agent(format!("tgltrk/{}", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(|e| AppError::Api(format!("Failed to build HTTP client: {e}")))?;

        Ok(Self { http, base_url })
    }

    pub fn new(api_token: &str) -> Result<Self> {
        Self::build(api_token, API_BASE_URL.to_string())
    }

    pub fn new_with_base_url(api_token: &str, base_url: &str) -> Result<Self> {
        Self::build(api_token, base_url.to_string())
    }

    async fn get<T: DeserializeOwned>(&self, url: &str) -> Result<T> {
        self.send(self.http.get(url)).await
    }

    async fn post<T: DeserializeOwned, B: Serialize>(&self, url: &str, body: &B) -> Result<T> {
        self.send(self.http.post(url).json(body)).await
    }

    async fn put<T: DeserializeOwned, B: Serialize>(&self, url: &str, body: &B) -> Result<T> {
        self.send(self.http.put(url).json(body)).await
    }

    async fn patch<T: DeserializeOwned, B: Serialize>(&self, url: &str, body: &B) -> Result<T> {
        self.send(self.http.patch(url).json(body)).await
    }

    async fn check_response(&self, response: reqwest::Response) -> Result<reqwest::Response> {
        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(AppError::HttpStatus {
                status: status.as_u16(),
                body,
            });
        }
        Ok(response)
    }

    async fn send<T: DeserializeOwned>(&self, request: RequestBuilder) -> Result<T> {
        let response = self.check_response(request.send().await?).await?;
        let parsed = response.json::<T>().await?;
        Ok(parsed)
    }

    async fn delete_request(&self, url: &str) -> Result<()> {
        self.check_response(self.http.delete(url).send().await?)
            .await?;
        Ok(())
    }
}

impl ApiClient for TogglClient {
    async fn get_me(&self) -> Result<User> {
        let url = format!("{}/me", self.base_url);
        let wire: WireUser = self.get(&url).await?;
        Ok(wire.into())
    }

    async fn get_current_timer(&self) -> Result<Option<TimeEntry>> {
        let url = format!("{}/me/time_entries/current", self.base_url);
        let response = self.http.get(&url).send().await?;
        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(AppError::HttpStatus {
                status: status.as_u16(),
                body,
            });
        }
        let text = response.text().await?;
        let text = text.trim();
        if text == "null" || text.is_empty() {
            return Ok(None);
        }
        let wire: WireTimeEntry = serde_json::from_str(text)?;
        Ok(Some(wire.into()))
    }

    async fn get_time_entries(
        &self,
        since: Option<String>,
        until: Option<String>,
    ) -> Result<Vec<TimeEntry>> {
        let url = format!("{}/me/time_entries", self.base_url);
        let mut request = self.http.get(&url);
        if let Some(s) = &since {
            request = request.query(&[("start_date", s)]);
        }
        if let Some(u) = &until {
            request = request.query(&[("end_date", u)]);
        }
        let response = self.check_response(request.send().await?).await?;
        let wire: Vec<WireTimeEntry> = response.json().await?;
        Ok(wire.into_iter().map(Into::into).collect())
    }

    async fn get_time_entry(&self, entry_id: TimeEntryId) -> Result<TimeEntry> {
        let url = format!("{}/me/time_entries/{entry_id}", self.base_url);
        let wire: WireTimeEntry = self.get(&url).await?;
        Ok(wire.into())
    }

    async fn create_time_entry(
        &self,
        workspace_id: WorkspaceId,
        params: &CreateTimeEntryParams,
    ) -> Result<TimeEntry> {
        let url = format!("{}/workspaces/{workspace_id}/time_entries", self.base_url);
        let now = Utc::now();
        let start = params.start.unwrap_or(now);
        let duration = params.duration.unwrap_or(-start.timestamp());
        let body = CreateTimeEntryRequest {
            workspace_id,
            description: params.description.clone(),
            project_id: params.project_id,
            task_id: params.task_id,
            tags: params.tags.clone(),
            billable: params.billable,
            start,
            duration,
            created_with: crate::constants::CLIENT_NAME.to_string(),
            stop: params.stop,
        };
        let wire: WireTimeEntry = self.post(&url, &body).await?;
        Ok(wire.into())
    }

    async fn update_time_entry(
        &self,
        workspace_id: WorkspaceId,
        entry_id: TimeEntryId,
        params: &UpdateTimeEntryParams,
    ) -> Result<TimeEntry> {
        let url = format!(
            "{}/workspaces/{workspace_id}/time_entries/{entry_id}",
            self.base_url
        );
        let body = UpdateTimeEntryRequest {
            description: params.description.clone(),
            project_id: params.project_id,
            tags: params.tags.clone(),
            billable: params.billable,
            start: params.start,
            stop: params.stop,
            duration: params.duration,
        };
        let wire: WireTimeEntry = self.put(&url, &body).await?;
        Ok(wire.into())
    }

    async fn delete_time_entry(
        &self,
        workspace_id: WorkspaceId,
        entry_id: TimeEntryId,
    ) -> Result<()> {
        let url = format!(
            "{}/workspaces/{workspace_id}/time_entries/{entry_id}",
            self.base_url
        );
        self.delete_request(&url).await
    }

    async fn stop_time_entry(
        &self,
        workspace_id: WorkspaceId,
        entry_id: TimeEntryId,
    ) -> Result<TimeEntry> {
        let url = format!(
            "{}/workspaces/{workspace_id}/time_entries/{entry_id}/stop",
            self.base_url
        );
        let wire: WireTimeEntry = self.patch(&url, &serde_json::json!({})).await?;
        Ok(wire.into())
    }

    async fn list_projects(&self, workspace_id: WorkspaceId) -> Result<Vec<Project>> {
        let url = format!("{}/workspaces/{workspace_id}/projects", self.base_url);
        let wire: Vec<WireProject> = self.get(&url).await?;
        Ok(wire.into_iter().map(Into::into).collect())
    }

    async fn get_project(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
    ) -> Result<Project> {
        let url = format!(
            "{}/workspaces/{workspace_id}/projects/{project_id}",
            self.base_url
        );
        let wire: WireProject = self.get(&url).await?;
        Ok(wire.into())
    }

    async fn create_project(
        &self,
        workspace_id: WorkspaceId,
        params: &CreateProjectParams,
    ) -> Result<Project> {
        let url = format!("{}/workspaces/{workspace_id}/projects", self.base_url);
        let body = CreateProjectRequest {
            name: params.name.clone(),
            active: true,
            client_id: params.client_id,
        };
        let wire: WireProject = self.post(&url, &body).await?;
        Ok(wire.into())
    }

    async fn update_project(
        &self,
        workspace_id: WorkspaceId,
        project_id: ProjectId,
        params: &UpdateProjectParams,
    ) -> Result<Project> {
        let url = format!(
            "{}/workspaces/{workspace_id}/projects/{project_id}",
            self.base_url
        );
        let body = UpdateProjectRequest {
            name: params.name.clone(),
            client_id: params.client_id,
        };
        let wire: WireProject = self.put(&url, &body).await?;
        Ok(wire.into())
    }

    async fn delete_project(&self, workspace_id: WorkspaceId, project_id: ProjectId) -> Result<()> {
        let url = format!(
            "{}/workspaces/{workspace_id}/projects/{project_id}",
            self.base_url
        );
        self.delete_request(&url).await
    }

    async fn list_tags(&self, workspace_id: WorkspaceId) -> Result<Vec<Tag>> {
        let url = format!("{}/workspaces/{workspace_id}/tags", self.base_url);
        let wire: Vec<WireTag> = self.get(&url).await?;
        Ok(wire.into_iter().map(Into::into).collect())
    }

    async fn create_tag(&self, workspace_id: WorkspaceId, name: &str) -> Result<Tag> {
        let url = format!("{}/workspaces/{workspace_id}/tags", self.base_url);
        let body = CreateTagRequest {
            name: name.to_string(),
        };
        let wire: WireTag = self.post(&url, &body).await?;
        Ok(wire.into())
    }

    async fn update_tag(
        &self,
        workspace_id: WorkspaceId,
        tag_id: TagId,
        name: &str,
    ) -> Result<Tag> {
        let url = format!("{}/workspaces/{workspace_id}/tags/{tag_id}", self.base_url);
        let body = UpdateTagRequest {
            name: name.to_string(),
        };
        let wire: WireTag = self.put(&url, &body).await?;
        Ok(wire.into())
    }

    async fn delete_tag(&self, workspace_id: WorkspaceId, tag_id: TagId) -> Result<()> {
        let url = format!("{}/workspaces/{workspace_id}/tags/{tag_id}", self.base_url);
        self.delete_request(&url).await
    }

    async fn list_clients(&self, workspace_id: WorkspaceId) -> Result<Vec<crate::models::Client>> {
        let url = format!("{}/workspaces/{workspace_id}/clients", self.base_url);
        let wire: Vec<WireClient> = self.get(&url).await?;
        Ok(wire.into_iter().map(Into::into).collect())
    }

    async fn create_client(
        &self,
        workspace_id: WorkspaceId,
        name: &str,
    ) -> Result<crate::models::Client> {
        let url = format!("{}/workspaces/{workspace_id}/clients", self.base_url);
        let body = CreateClientRequest {
            name: name.to_string(),
        };
        let wire: WireClient = self.post(&url, &body).await?;
        Ok(wire.into())
    }

    async fn update_client(
        &self,
        workspace_id: WorkspaceId,
        client_id: ClientId,
        name: &str,
    ) -> Result<crate::models::Client> {
        let url = format!(
            "{}/workspaces/{workspace_id}/clients/{client_id}",
            self.base_url
        );
        let body = UpdateClientRequest {
            name: name.to_string(),
        };
        let wire: WireClient = self.put(&url, &body).await?;
        Ok(wire.into())
    }

    async fn delete_client(&self, workspace_id: WorkspaceId, client_id: ClientId) -> Result<()> {
        let url = format!(
            "{}/workspaces/{workspace_id}/clients/{client_id}",
            self.base_url
        );
        self.delete_request(&url).await
    }

    async fn get_client(
        &self,
        workspace_id: WorkspaceId,
        client_id: ClientId,
    ) -> Result<crate::models::Client> {
        let url = format!(
            "{}/workspaces/{workspace_id}/clients/{client_id}",
            self.base_url
        );
        let wire: WireClient = self.get(&url).await?;
        Ok(wire.into())
    }

    async fn list_workspaces(&self) -> Result<Vec<crate::models::Workspace>> {
        let url = format!("{}/me/workspaces", self.base_url);
        let wire: Vec<WireWorkspace> = self.get(&url).await?;
        Ok(wire.into_iter().map(Into::into).collect())
    }

    async fn get_workspace(&self, workspace_id: WorkspaceId) -> Result<crate::models::Workspace> {
        let url = format!("{}/workspaces/{workspace_id}", self.base_url);
        let wire: WireWorkspace = self.get(&url).await?;
        Ok(wire.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    async fn setup() -> (MockServer, TogglClient) {
        let server = MockServer::start().await;
        let client = TogglClient::new_with_base_url("test_token", &server.uri()).unwrap();
        (server, client)
    }

    fn wire_user_json() -> serde_json::Value {
        serde_json::json!({
            "email": "test@example.com",
            "fullname": "Test User",
            "default_workspace_id": 1,
            "timezone": "UTC"
        })
    }

    fn wire_time_entry_json(id: i64, workspace_id: i64) -> serde_json::Value {
        serde_json::json!({
            "id": id,
            "workspace_id": workspace_id,
            "description": "Test entry",
            "start": "2024-01-01T00:00:00Z",
            "stop": "2024-01-01T01:00:00Z",
            "duration": 3600,
            "project_id": null,
            "task_id": null,
            "tags": [],
            "billable": false
        })
    }

    fn wire_project_json(id: i64, workspace_id: i64) -> serde_json::Value {
        serde_json::json!({
            "id": id,
            "workspace_id": workspace_id,
            "name": "Test Project",
            "active": true,
            "color": "#06aaf5",
            "billable": null
        })
    }

    fn wire_tag_json(id: i64, workspace_id: i64) -> serde_json::Value {
        serde_json::json!({
            "id": id,
            "workspace_id": workspace_id,
            "name": "Test Tag"
        })
    }

    #[test]
    fn new_with_valid_token_succeeds() {
        assert!(TogglClient::new("valid_token").is_ok());
    }

    #[test]
    fn new_with_empty_token_succeeds() {
        assert!(TogglClient::new("").is_ok());
    }

    // --- get_me ---

    #[tokio::test]
    async fn get_me_returns_user() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_user_json()))
            .mount(&server)
            .await;

        let user = client.get_me().await.unwrap();
        assert_eq!(user.email, "test@example.com");
        assert_eq!(user.fullname, "Test User");
        assert_eq!(user.default_workspace_id, WorkspaceId(1));
    }

    // --- get_current_timer ---

    #[tokio::test]
    async fn get_current_timer_running() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me/time_entries/current"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_time_entry_json(42, 1)))
            .mount(&server)
            .await;

        let result = client.get_current_timer().await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().id, TimeEntryId(42));
    }

    #[tokio::test]
    async fn get_current_timer_null() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me/time_entries/current"))
            .respond_with(ResponseTemplate::new(200).set_body_string("null"))
            .mount(&server)
            .await;

        let result = client.get_current_timer().await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn get_current_timer_empty() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me/time_entries/current"))
            .respond_with(ResponseTemplate::new(200).set_body_string(""))
            .mount(&server)
            .await;

        let result = client.get_current_timer().await.unwrap();
        assert!(result.is_none());
    }

    // --- get_time_entries ---

    #[tokio::test]
    async fn get_time_entries_no_params() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me/time_entries"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([wire_time_entry_json(1, 1)])),
            )
            .mount(&server)
            .await;

        let entries = client.get_time_entries(None, None).await.unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].id, TimeEntryId(1));
    }

    #[tokio::test]
    async fn get_time_entries_with_since_until() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me/time_entries"))
            .and(query_param("start_date", "2024-01-01"))
            .and(query_param("end_date", "2024-01-31"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([wire_time_entry_json(1, 1)])),
            )
            .mount(&server)
            .await;

        let entries = client
            .get_time_entries(
                Some("2024-01-01".to_string()),
                Some("2024-01-31".to_string()),
            )
            .await
            .unwrap();
        assert_eq!(entries.len(), 1);
    }

    // --- get_time_entry ---

    #[tokio::test]
    async fn get_time_entry_by_id() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me/time_entries/42"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_time_entry_json(42, 1)))
            .mount(&server)
            .await;

        let entry = client.get_time_entry(TimeEntryId(42)).await.unwrap();
        assert_eq!(entry.id, TimeEntryId(42));
    }

    // --- create_time_entry ---

    #[tokio::test]
    async fn create_time_entry_sends_post() {
        let (server, client) = setup().await;
        Mock::given(method("POST"))
            .and(path("/workspaces/1/time_entries"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_time_entry_json(100, 1)))
            .mount(&server)
            .await;

        let params = CreateTimeEntryParams {
            description: Some("Test".to_string()),
            project_id: None,
            task_id: None,
            tags: vec![],
            billable: false,
            start: None,
            stop: None,
            duration: None,
        };
        let entry = client
            .create_time_entry(WorkspaceId(1), &params)
            .await
            .unwrap();
        assert_eq!(entry.id, TimeEntryId(100));
    }

    // --- update_time_entry ---

    #[tokio::test]
    async fn update_time_entry_sends_put() {
        let (server, client) = setup().await;
        Mock::given(method("PUT"))
            .and(path("/workspaces/1/time_entries/42"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_time_entry_json(42, 1)))
            .mount(&server)
            .await;

        let params = UpdateTimeEntryParams {
            description: Some("Updated".to_string()),
            project_id: None,
            tags: None,
            billable: None,
            start: None,
            stop: None,
            duration: None,
        };
        let entry = client
            .update_time_entry(WorkspaceId(1), TimeEntryId(42), &params)
            .await
            .unwrap();
        assert_eq!(entry.id, TimeEntryId(42));
    }

    // --- delete_time_entry ---

    #[tokio::test]
    async fn delete_time_entry_sends_delete() {
        let (server, client) = setup().await;
        Mock::given(method("DELETE"))
            .and(path("/workspaces/1/time_entries/42"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&server)
            .await;

        let result = client
            .delete_time_entry(WorkspaceId(1), TimeEntryId(42))
            .await;
        assert!(result.is_ok());
    }

    // --- stop_time_entry ---

    #[tokio::test]
    async fn stop_time_entry_sends_patch() {
        let (server, client) = setup().await;
        Mock::given(method("PATCH"))
            .and(path("/workspaces/1/time_entries/42/stop"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_time_entry_json(42, 1)))
            .mount(&server)
            .await;

        let entry = client
            .stop_time_entry(WorkspaceId(1), TimeEntryId(42))
            .await
            .unwrap();
        assert_eq!(entry.id, TimeEntryId(42));
    }

    // --- projects ---

    #[tokio::test]
    async fn list_projects_returns_vec() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/workspaces/1/projects"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([wire_project_json(10, 1)])),
            )
            .mount(&server)
            .await;

        let projects = client.list_projects(WorkspaceId(1)).await.unwrap();
        assert_eq!(projects.len(), 1);
        assert_eq!(projects[0].id, ProjectId(10));
    }

    #[tokio::test]
    async fn get_project_by_id() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/workspaces/1/projects/10"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_project_json(10, 1)))
            .mount(&server)
            .await;

        let project = client
            .get_project(WorkspaceId(1), ProjectId(10))
            .await
            .unwrap();
        assert_eq!(project.id, ProjectId(10));
    }

    #[tokio::test]
    async fn create_project_sends_post() {
        let (server, client) = setup().await;
        Mock::given(method("POST"))
            .and(path("/workspaces/1/projects"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_project_json(11, 1)))
            .mount(&server)
            .await;

        let params = CreateProjectParams {
            name: "New Project".to_string(),
            client_id: None,
        };
        let project = client
            .create_project(WorkspaceId(1), &params)
            .await
            .unwrap();
        assert_eq!(project.id, ProjectId(11));
    }

    #[tokio::test]
    async fn update_project_sends_put() {
        let (server, client) = setup().await;
        Mock::given(method("PUT"))
            .and(path("/workspaces/1/projects/10"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_project_json(10, 1)))
            .mount(&server)
            .await;

        let params = UpdateProjectParams {
            name: Some("Renamed".to_string()),
            client_id: None,
        };
        let project = client
            .update_project(WorkspaceId(1), ProjectId(10), &params)
            .await
            .unwrap();
        assert_eq!(project.id, ProjectId(10));
    }

    #[tokio::test]
    async fn delete_project_sends_delete() {
        let (server, client) = setup().await;
        Mock::given(method("DELETE"))
            .and(path("/workspaces/1/projects/10"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&server)
            .await;

        let result = client.delete_project(WorkspaceId(1), ProjectId(10)).await;
        assert!(result.is_ok());
    }

    // --- tags ---

    #[tokio::test]
    async fn list_tags_returns_vec() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/workspaces/1/tags"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([wire_tag_json(5, 1)])),
            )
            .mount(&server)
            .await;

        let tags = client.list_tags(WorkspaceId(1)).await.unwrap();
        assert_eq!(tags.len(), 1);
        assert_eq!(tags[0].id, TagId(5));
    }

    #[tokio::test]
    async fn create_tag_sends_post() {
        let (server, client) = setup().await;
        Mock::given(method("POST"))
            .and(path("/workspaces/1/tags"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_tag_json(6, 1)))
            .mount(&server)
            .await;

        let tag = client.create_tag(WorkspaceId(1), "New Tag").await.unwrap();
        assert_eq!(tag.id, TagId(6));
    }

    #[tokio::test]
    async fn update_tag_sends_put() {
        let (server, client) = setup().await;
        Mock::given(method("PUT"))
            .and(path("/workspaces/1/tags/5"))
            .respond_with(ResponseTemplate::new(200).set_body_json(wire_tag_json(5, 1)))
            .mount(&server)
            .await;

        let tag = client
            .update_tag(WorkspaceId(1), TagId(5), "Renamed")
            .await
            .unwrap();
        assert_eq!(tag.id, TagId(5));
    }

    #[tokio::test]
    async fn delete_tag_sends_delete() {
        let (server, client) = setup().await;
        Mock::given(method("DELETE"))
            .and(path("/workspaces/1/tags/5"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&server)
            .await;

        let result = client.delete_tag(WorkspaceId(1), TagId(5)).await;
        assert!(result.is_ok());
    }

    // --- From<&TimeEntry> for CreateTimeEntryParams ---

    #[test]
    fn from_time_entry_to_create_params() {
        use crate::models::TimeEntry;
        use chrono::Utc;

        let now = Utc::now();
        let entry = TimeEntry {
            id: TimeEntryId(42),
            workspace_id: WorkspaceId(1),
            description: Some("My task".to_string()),
            start: now,
            stop: Some(now),
            duration: 3600,
            project_id: Some(ProjectId(10)),
            task_id: Some(TaskId(20)),
            tags: vec!["a".to_string(), "b".to_string()],
            billable: true,
        };

        let params = CreateTimeEntryParams::from(&entry);

        assert_eq!(params.description, entry.description);
        assert_eq!(params.project_id, entry.project_id);
        assert_eq!(params.task_id, entry.task_id);
        assert_eq!(params.tags, entry.tags);
        assert_eq!(params.billable, entry.billable);
    }

    // --- error cases ---

    #[tokio::test]
    async fn send_http_401_returns_error() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me"))
            .respond_with(ResponseTemplate::new(401).set_body_string("Unauthorized"))
            .mount(&server)
            .await;

        let result = client.get_me().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            AppError::HttpStatus { status, body } => {
                assert_eq!(status, 401);
                assert_eq!(body, "Unauthorized");
            }
            other => panic!("expected HttpStatus, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn send_http_500_returns_error() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me"))
            .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
            .mount(&server)
            .await;

        let result = client.get_me().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            AppError::HttpStatus { status, .. } => assert_eq!(status, 500),
            other => panic!("expected HttpStatus, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn get_current_timer_http_error() {
        let (server, client) = setup().await;
        Mock::given(method("GET"))
            .and(path("/me/time_entries/current"))
            .respond_with(ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;

        let result = client.get_current_timer().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            AppError::HttpStatus { status, .. } => assert_eq!(status, 403),
            other => panic!("expected HttpStatus, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn delete_request_http_error() {
        let (server, client) = setup().await;
        Mock::given(method("DELETE"))
            .and(path("/workspaces/1/tags/1"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;

        let result = client.delete_tag(WorkspaceId(1), TagId(1)).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            AppError::HttpStatus { status, .. } => assert_eq!(status, 404),
            other => panic!("expected HttpStatus, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn connection_refused_returns_api_error() {
        let client = TogglClient::new_with_base_url("test_token", "http://127.0.0.1:1").unwrap();
        let result = client.get_me().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            AppError::Api(_) => {}
            other => panic!("expected Api error, got: {other:?}"),
        }
    }
}