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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
from __future__ import annotations

import time
from typing import Any, Dict, Optional

from fastapi import APIRouter, Depends, Header, HTTPException

from app.config import get_settings
from app.core.logger import get_logger
from app.models.schemas import (
    GmailAttachmentContent,
    GmailBatchDeleteRequest,
    GmailBatchModifyRequest,
    GmailComposeMessageRequest,
    GmailDraftCreateRequest,
    GmailDraftSendRequest,
    GmailDraftUpdateRequest,
    GmailFilterCreateRequest,
    GmailGenericResponse,
    GmailImportMessageRequest,
    GmailInsertMessageRequest,
    GmailLabelPatchRequest,
    GmailLabelRequest,
    GmailMessageModifyRequest,
    GmailRawMessageRequest,
    GmailRefreshResponse,
    GmailSendResponse,
    GmailSettingsUpdateRequest,
    GmailSmimeInfoRequest,
    GmailWatchRequest,
)
from app.services.gmail_service import (
    GmailAPIError,
    GmailCredentials,
    GmailService,
)

router = APIRouter(prefix="/google/gmail", tags=["Gmail"])
_logger = get_logger(__name__)
_settings = get_settings()

_gmail_service = GmailService()


def get_gmail_service() -> GmailService:
    return _gmail_service


async def close_gmail_service() -> None:
    await _gmail_service.close()


def _credentials(
    x_access_token: Optional[str] = Header(None, alias="X-Access-Token"),
    x_refresh_token: Optional[str] = Header(None, alias="X-Refresh-Token"),
    x_client_id: Optional[str] = Header(None, alias="X-Client-Id"),
    x_client_secret: Optional[str] = Header(None, alias="X-Client-Secret"),
    x_token_expires_at: Optional[float] = Header(None, alias="X-Token-Expires-At"),
) -> GmailCredentials:
    if not x_access_token:
        raise HTTPException(
            status_code=401,
            detail="X-Access-Token header is required.",
        )
    return GmailCredentials(
        access_token=x_access_token,
        refresh_token=x_refresh_token,
        client_id=x_client_id,
        client_secret=x_client_secret,
        expires_at=x_token_expires_at,
    )


def _http_error(exc: GmailAPIError) -> HTTPException:
    return HTTPException(status_code=exc.status_code, detail=exc.message)


def _elapsed_ms(start: float) -> float:
    return round((time.perf_counter() - start) * 1000, 2)


def _ok(
    start: float,
    creds: GmailCredentials,
    data: Any = None,
    *,
    error: Optional[str] = None,
) -> GmailGenericResponse:
    return GmailGenericResponse(
        success=error is None,
        time_ms=_elapsed_ms(start),
        data=data,
        refreshed_access_token=creds.refreshed_access_token,
        error=error,
    )


def _user_id(delegate: str) -> str:
    return delegate or "me"


def _attachment_content(
    message_id: str,
    attachment_id: str,
    raw: Dict[str, Any],
) -> GmailAttachmentContent:
    return GmailAttachmentContent(
        message_id=message_id,
        attachment_id=attachment_id,
        filename=raw.get("filename", ""),
        mime_type=raw.get("mimeType", ""),
        data_base64=raw.get("data", ""),
        size_bytes=int(raw.get("size", 0) or 0),
    )


# ---------------------------------------------------------------------------
# Service metadata & token lifecycle
# ---------------------------------------------------------------------------

@router.get("/scopes", response_model=GmailGenericResponse,
            summary="List all supported Gmail OAuth scopes")
async def list_scopes(
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    scopes = await service.list_available_scopes()
    _logger.info("Listed %d Gmail scopes (%.2fms)", len(scopes), _elapsed_ms(start))
    return GmailGenericResponse(success=True, time_ms=_elapsed_ms(start), data=scopes)


@router.post("/token/refresh", response_model=GmailRefreshResponse,
             summary="Refresh an access token (stateless, returned to the client)")
async def token_refresh(
    body: Dict[str, str],
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    client_id = body.get("client_id", "")
    client_secret = body.get("client_secret", "")
    refresh_token = body.get("refresh_token", "")
    if not (client_id and client_secret and refresh_token):
        raise HTTPException(
            status_code=400,
            detail="client_id, client_secret and refresh_token are required.",
        )
    try:
        tokens = await service.refresh_access_token(
            client_id=client_id,
            client_secret=client_secret,
            refresh_token=refresh_token,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail token refreshed (%.2fms)", _elapsed_ms(start))
    return GmailRefreshResponse(
        success=True,
        access_token=tokens.get("access_token"),
        expires_in=int(tokens.get("expires_in", 0)),
        token_type=tokens.get("token_type", "Bearer"),
        scope=tokens.get("scope"),
    )


# ---------------------------------------------------------------------------
# Profile
# ---------------------------------------------------------------------------

@router.get("/profile", response_model=GmailGenericResponse,
            summary="Get the authenticated user's Gmail profile")
async def get_profile(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.get_profile(creds)
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail profile fetched (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


# ---------------------------------------------------------------------------
# Watch / Stop / History (push notifications & change history)
# ---------------------------------------------------------------------------

@router.post("/watch", response_model=GmailGenericResponse,
             summary="Set up push notifications for mailbox changes (users.watch)")
async def watch_mailbox(
    body: GmailWatchRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.watch(
            creds,
            user_id=body.user_id,
            topic_name=body.topic_name,
            label_ids=body.label_ids,
            label_filter_action=body.label_filter_action,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail watch enabled for %s (%.2fms)", body.user_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/stop", response_model=GmailGenericResponse,
             summary="Stop receiving push notifications (users.stop)")
async def stop_watch_mailbox(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.stop_watch(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail watch stopped (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, {"stopped": True})


@router.get("/history", response_model=GmailGenericResponse,
            summary="List mailbox change history (users.history.list)")
async def list_history(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    start_history_id: int = ...,
    label_id: Optional[str] = None,
    history_types: Optional[str] = None,
    max_results: Optional[int] = None,
    page_token: Optional[str] = None,
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_history(
            creds,
            user_id=user_id or "me",
            start_history_id=start_history_id,
            label_id=label_id,
            history_types=history_types.split(",") if history_types else None,
            max_results=max_results,
            page_token=page_token,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail history listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


# ---------------------------------------------------------------------------
# Messages
# ---------------------------------------------------------------------------

@router.get("/messages", response_model=GmailGenericResponse,
            summary="List messages (supports Gmail search query and pagination)")
async def list_messages(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    q: Optional[str] = None,
    label_ids: Optional[str] = None,
    max_results: Optional[int] = None,
    page_token: Optional[str] = None,
    include_spam_trash: bool = False,
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_messages(
            creds,
            user_id=user_id or "me",
            q=q,
            label_ids=label_ids.split(",") if label_ids else None,
            max_results=max_results,
            page_token=page_token,
            include_spam_trash=include_spam_trash,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail messages listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/messages/{message_id}", response_model=GmailGenericResponse,
            summary="Get a single message (format: minimal, metadata, full, raw)")
async def get_message(
    message_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    format: str = "full",
    metadata_headers: Optional[str] = None,
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_message(
            creds,
            message_id,
            user_id=user_id or "me",
            format=format,
            metadata_headers=metadata_headers.split(",") if metadata_headers else None,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message %s fetched (%.2fms)", message_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/messages/{message_id}/parsed", response_model=GmailGenericResponse,
            summary="Get a message parsed into headers, bodies and attachment metadata")
async def get_parsed_message(
    message_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        parsed = await service.get_parsed_message(creds, message_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message %s parsed (%.2fms)", message_id, _elapsed_ms(start))
    return _ok(start, creds, parsed.model_dump())


@router.get("/messages/{message_id}/attachments/{attachment_id}",
            response_model=GmailGenericResponse,
            summary="Get a message attachment's content (base64url)")
async def get_attachment(
    message_id: str,
    attachment_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        raw = await service.get_attachment(
            creds, message_id, attachment_id, user_id=user_id or "me"
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    content = _attachment_content(message_id, attachment_id, raw)
    _logger.info(
        "Gmail attachment %s fetched for message %s (%.2fms)",
        attachment_id,
        message_id,
        _elapsed_ms(start),
    )
    return _ok(start, creds, content.model_dump())


@router.post("/messages/send", response_model=GmailSendResponse,
             summary="Send an email built from a structured compose request")
async def send_composed(
    body: GmailComposeMessageRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.send_composed(creds, body, user_id=_user_id(body.delegate))
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail email sent (%.2fms)", _elapsed_ms(start))
    return GmailSendResponse(
        success=True,
        time_ms=_elapsed_ms(start),
        message_id=data.get("id"),
        thread_id=data.get("threadId"),
        label_ids=data.get("labelIds"),
        refreshed_access_token=creds.refreshed_access_token,
        data=data,
    )


@router.post("/messages/send/raw", response_model=GmailSendResponse,
             summary="Send a pre-encoded RFC 2822 message")
async def send_raw(
    body: GmailRawMessageRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.send_raw(
            creds,
            body.raw,
            user_id=_user_id(body.delegate),
            thread_id=body.thread_id,
            labels=body.labels,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail raw message sent (%.2fms)", _elapsed_ms(start))
    return GmailSendResponse(
        success=True,
        time_ms=_elapsed_ms(start),
        message_id=data.get("id"),
        thread_id=data.get("threadId"),
        label_ids=data.get("labelIds"),
        refreshed_access_token=creds.refreshed_access_token,
        data=data,
    )


@router.post("/messages", response_model=GmailSendResponse,
             summary="Insert a message directly into the mailbox (does not send)")
async def insert_message(
    body: GmailInsertMessageRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.insert_message(
            creds,
            body.raw,
            user_id=_user_id(body.delegate),
            label_ids=body.label_ids,
            internal_date_source=body.internal_date_source,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message inserted (%.2fms)", _elapsed_ms(start))
    return GmailSendResponse(
        success=True,
        time_ms=_elapsed_ms(start),
        message_id=data.get("id"),
        thread_id=data.get("threadId"),
        refreshed_access_token=creds.refreshed_access_token,
        data=data,
    )


@router.post("/messages/import", response_model=GmailSendResponse,
             summary="Import an RFC 2822 message into the mailbox (users.messages.import)")
async def import_message(
    body: GmailImportMessageRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.import_message(
            creds,
            body.raw,
            user_id=_user_id(body.delegate),
            label_ids=body.label_ids,
            internal_date_source=body.internal_date_source,
            never_mark_spam=body.never_mark_spam,
            process_for_calendar=body.process_for_calendar,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message imported (%.2fms)", _elapsed_ms(start))
    return GmailSendResponse(
        success=True,
        time_ms=_elapsed_ms(start),
        message_id=data.get("id"),
        thread_id=data.get("threadId"),
        refreshed_access_token=creds.refreshed_access_token,
        data=data,
    )


@router.post("/messages/batchModify", response_model=GmailGenericResponse,
             summary="Add/remove labels across many messages")
async def batch_modify(
    body: GmailBatchModifyRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        await service.batch_modify(
            creds,
            body.ids,
            user_id="me",
            add_label_ids=body.add_label_ids,
            remove_label_ids=body.remove_label_ids,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail batch modify on %d messages (%.2fms)", len(body.ids), _elapsed_ms(start))
    return _ok(start, creds, {"modified": len(body.ids)})


@router.post("/messages/batchDelete", response_model=GmailGenericResponse,
             summary="Permanently delete many messages")
async def batch_delete(
    body: GmailBatchDeleteRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        await service.batch_delete(creds, body.ids, user_id="me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail batch delete on %d messages (%.2fms)", len(body.ids), _elapsed_ms(start))
    return _ok(start, creds, {"deleted": len(body.ids)})


@router.post("/messages/{message_id}/modify", response_model=GmailGenericResponse,
             summary="Add/remove labels on a single message (e.g. mark read/unread)")
async def modify_message(
    message_id: str,
    body: GmailMessageModifyRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.modify_message(
            creds,
            message_id,
            user_id=user_id or "me",
            add_label_ids=body.add_label_ids,
            remove_label_ids=body.remove_label_ids,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message %s modified (%.2fms)", message_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/messages/{message_id}/trash", response_model=GmailGenericResponse,
             summary="Move a message to trash")
async def trash_message(
    message_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.trash_message(creds, message_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message %s trashed (%.2fms)", message_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/messages/{message_id}/untrash", response_model=GmailGenericResponse,
             summary="Restore a message from trash")
async def untrash_message(
    message_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.untrash_message(creds, message_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message %s untrashed (%.2fms)", message_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/messages/{message_id}", response_model=GmailGenericResponse,
               summary="Permanently delete a message")
async def delete_message(
    message_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_message(creds, message_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail message %s deleted (%.2fms)", message_id, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": message_id})


# ---------------------------------------------------------------------------
# Drafts
# ---------------------------------------------------------------------------

@router.get("/drafts", response_model=GmailGenericResponse,
            summary="List drafts")
async def list_drafts(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    max_results: Optional[int] = None,
    page_token: Optional[str] = None,
    q: Optional[str] = None,
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_drafts(
            creds,
            user_id=user_id or "me",
            max_results=max_results,
            page_token=page_token,
            q=q,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail drafts listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/drafts/{draft_id}", response_model=GmailGenericResponse,
            summary="Get a single draft")
async def get_draft(
    draft_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    format: str = "full",
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_draft(creds, draft_id, user_id=user_id or "me", format=format)
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail draft %s fetched (%.2fms)", draft_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/drafts", response_model=GmailGenericResponse,
             summary="Create a draft from a pre-encoded RFC 2822 message")
async def create_draft(
    body: GmailDraftCreateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.create_draft(
            creds,
            body.raw,
            user_id=_user_id(body.delegate),
            thread_id=body.thread_id,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail draft created (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.put("/drafts/{draft_id}", response_model=GmailGenericResponse,
            summary="Replace an existing draft")
async def update_draft(
    draft_id: str,
    body: GmailDraftUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.update_draft(
            creds,
            draft_id,
            body.raw,
            user_id=_user_id(body.delegate),
            thread_id=body.thread_id,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail draft %s updated (%.2fms)", draft_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/drafts/send", response_model=GmailSendResponse,
             summary="Send an existing draft")
async def send_draft(
    body: GmailDraftSendRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
):
    start = time.perf_counter()
    try:
        data = await service.send_draft(creds, body.draft_id, user_id=_user_id(body.delegate))
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail draft %s sent (%.2fms)", body.draft_id, _elapsed_ms(start))
    return GmailSendResponse(
        success=True,
        time_ms=_elapsed_ms(start),
        message_id=data.get("id"),
        thread_id=data.get("threadId"),
        refreshed_access_token=creds.refreshed_access_token,
        data=data,
    )


@router.delete("/drafts/{draft_id}", response_model=GmailGenericResponse,
               summary="Delete a draft")
async def delete_draft(
    draft_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_draft(creds, draft_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail draft %s deleted (%.2fms)", draft_id, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": draft_id})


# ---------------------------------------------------------------------------
# Threads
# ---------------------------------------------------------------------------

@router.get("/threads", response_model=GmailGenericResponse,
            summary="List threads")
async def list_threads(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    q: Optional[str] = None,
    label_ids: Optional[str] = None,
    max_results: Optional[int] = None,
    page_token: Optional[str] = None,
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_threads(
            creds,
            user_id=user_id or "me",
            q=q,
            label_ids=label_ids.split(",") if label_ids else None,
            max_results=max_results,
            page_token=page_token,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail threads listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/threads/{thread_id}", response_model=GmailGenericResponse,
            summary="Get a single thread with all its messages")
async def get_thread(
    thread_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    format: str = "full",
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_thread(creds, thread_id, user_id=user_id or "me", format=format)
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail thread %s fetched (%.2fms)", thread_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/threads/{thread_id}/modify", response_model=GmailGenericResponse,
             summary="Add/remove labels on all messages in a thread")
async def modify_thread(
    thread_id: str,
    body: GmailMessageModifyRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.modify_thread(
            creds,
            thread_id,
            user_id=user_id or "me",
            add_label_ids=body.add_label_ids,
            remove_label_ids=body.remove_label_ids,
        )
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail thread %s modified (%.2fms)", thread_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/threads/{thread_id}/trash", response_model=GmailGenericResponse,
             summary="Move all messages in a thread to trash")
async def trash_thread(
    thread_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.trash_thread(creds, thread_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail thread %s trashed (%.2fms)", thread_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/threads/{thread_id}/untrash", response_model=GmailGenericResponse,
             summary="Restore all messages in a thread from trash")
async def untrash_thread(
    thread_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.untrash_thread(creds, thread_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail thread %s untrashed (%.2fms)", thread_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/threads/{thread_id}", response_model=GmailGenericResponse,
               summary="Permanently delete a thread")
async def delete_thread(
    thread_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_thread(creds, thread_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail thread %s deleted (%.2fms)", thread_id, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": thread_id})


# ---------------------------------------------------------------------------
# Labels
# ---------------------------------------------------------------------------

@router.get("/labels", response_model=GmailGenericResponse,
            summary="List all labels")
async def list_labels(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_labels(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail labels listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/labels/{label_id}", response_model=GmailGenericResponse,
            summary="Get a single label")
async def get_label(
    label_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_label(creds, label_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail label %s fetched (%.2fms)", label_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/labels", response_model=GmailGenericResponse,
             summary="Create a user label")
async def create_label(
    body: GmailLabelRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.create_label(creds, body, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail label '%s' created (%.2fms)", body.name, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.put("/labels/{label_id}", response_model=GmailGenericResponse,
            summary="Update a user label")
async def update_label(
    label_id: str,
    body: GmailLabelRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.update_label(creds, label_id, body, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail label %s updated (%.2fms)", label_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.patch("/labels/{label_id}", response_model=GmailGenericResponse,
              summary="Partially update a user label (users.labels.patch)")
async def patch_label(
    label_id: str,
    body: GmailLabelPatchRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    payload = body.model_dump(exclude_none=True)
    if not payload:
        raise HTTPException(
            status_code=400,
            detail="At least one label field (name, label_list_visibility, message_list_visibility, color) is required.",
        )
    try:
        data = await service.patch_label(creds, label_id, payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail label %s patched (%.2fms)", label_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/labels/{label_id}", response_model=GmailGenericResponse,
               summary="Delete a user label")
async def delete_label(
    label_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_label(creds, label_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail label %s deleted (%.2fms)", label_id, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": label_id})


# ---------------------------------------------------------------------------
# Settings
# ---------------------------------------------------------------------------

@router.get("/settings/auto-forwarding", response_model=GmailGenericResponse,
            summary="Get auto-forwarding settings")
async def get_auto_forwarding(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_auto_forwarding(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail auto-forwarding fetched (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.put("/settings/auto-forwarding", response_model=GmailGenericResponse,
            summary="Update auto-forwarding settings")
async def update_auto_forwarding(
    body: GmailSettingsUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.update_auto_forwarding(creds, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail auto-forwarding updated (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/vacation", response_model=GmailGenericResponse,
            summary="Get vacation responder settings")
async def get_vacation(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_vacation(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail vacation settings fetched (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.put("/settings/vacation", response_model=GmailGenericResponse,
            summary="Update vacation responder settings")
async def update_vacation(
    body: GmailSettingsUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.update_vacation(creds, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail vacation settings updated (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/imap", response_model=GmailGenericResponse,
            summary="Get IMAP settings")
async def get_imap(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_imap(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail IMAP settings fetched (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.put("/settings/imap", response_model=GmailGenericResponse,
            summary="Update IMAP settings")
async def update_imap(
    body: GmailSettingsUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.update_imap(creds, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail IMAP settings updated (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/pop", response_model=GmailGenericResponse,
            summary="Get POP settings")
async def get_pop(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_pop(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail POP settings fetched (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.put("/settings/pop", response_model=GmailGenericResponse,
            summary="Update POP settings")
async def update_pop(
    body: GmailSettingsUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.update_pop(creds, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail POP settings updated (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/language", response_model=GmailGenericResponse,
            summary="Get language settings")
async def get_language(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_language(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail language settings fetched (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.put("/settings/language", response_model=GmailGenericResponse,
            summary="Update language settings")
async def update_language(
    body: GmailSettingsUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.update_language(creds, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail language settings updated (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/filters", response_model=GmailGenericResponse,
            summary="List all filters")
async def list_filters(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_filters(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail filters listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/filters/{filter_id}", response_model=GmailGenericResponse,
            summary="Get a single filter")
async def get_filter(
    filter_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_filter(creds, filter_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail filter %s fetched (%.2fms)", filter_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/settings/filters", response_model=GmailGenericResponse,
             summary="Create a filter")
async def create_filter(
    body: GmailFilterCreateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.create_filter(creds, body, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail filter created (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/settings/filters/{filter_id}", response_model=GmailGenericResponse,
               summary="Delete a filter")
async def delete_filter(
    filter_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_filter(creds, filter_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail filter %s deleted (%.2fms)", filter_id, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": filter_id})


@router.get("/settings/forwarding-addresses", response_model=GmailGenericResponse,
            summary="List forwarding addresses")
async def list_forwarding_addresses(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_forwarding_addresses(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail forwarding addresses listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/forwarding-addresses/{forwarding_email}", response_model=GmailGenericResponse,
            summary="Get a forwarding address")
async def get_forwarding_address(
    forwarding_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_forwarding_address(creds, forwarding_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail forwarding address %s fetched (%.2fms)", forwarding_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/settings/forwarding-addresses", response_model=GmailGenericResponse,
             summary="Create a forwarding address")
async def create_forwarding_address(
    body: Dict[str, str],
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    forwarding_email = body.get("forwarding_email", "")
    if not forwarding_email:
        raise HTTPException(status_code=400, detail="forwarding_email is required.")
    try:
        data = await service.create_forwarding_address(creds, forwarding_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail forwarding address %s created (%.2fms)", forwarding_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/settings/forwarding-addresses/{forwarding_email}", response_model=GmailGenericResponse,
               summary="Delete a forwarding address")
async def delete_forwarding_address(
    forwarding_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_forwarding_address(creds, forwarding_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail forwarding address %s deleted (%.2fms)", forwarding_email, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": forwarding_email})


@router.get("/settings/send-as", response_model=GmailGenericResponse,
            summary="List send-as aliases")
async def list_send_as(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_send_as(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail send-as aliases listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/send-as/{send_as_email}", response_model=GmailGenericResponse,
            summary="Get a send-as alias")
async def get_send_as(
    send_as_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_send_as(creds, send_as_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail send-as %s fetched (%.2fms)", send_as_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/settings/send-as", response_model=GmailGenericResponse,
             summary="Create a send-as alias")
async def create_send_as(
    body: GmailSettingsUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.create_send_as(creds, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail send-as created (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.patch("/settings/send-as/{send_as_email}", response_model=GmailGenericResponse,
              summary="Update a send-as alias")
async def update_send_as(
    send_as_email: str,
    body: GmailSettingsUpdateRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.update_send_as(creds, send_as_email, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail send-as %s updated (%.2fms)", send_as_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/settings/send-as/{send_as_email}", response_model=GmailGenericResponse,
               summary="Delete a send-as alias")
async def delete_send_as(
    send_as_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_send_as(creds, send_as_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail send-as %s deleted (%.2fms)", send_as_email, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": send_as_email})


@router.post("/settings/send-as/{send_as_email}/verify", response_model=GmailGenericResponse,
             summary="Send a verification email for a send-as alias (users.settings.sendAs.verify)")
async def verify_send_as(
    send_as_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.verify_send_as(creds, send_as_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail send-as %s verification triggered (%.2fms)", send_as_email, _elapsed_ms(start))
    return _ok(start, creds, {"verification_sent": send_as_email})


@router.get("/settings/send-as/{send_as_email}/smime-info", response_model=GmailGenericResponse,
            summary="List S/MIME certificates for a send-as alias (smimeInfo.list)")
async def list_smime_info(
    send_as_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_smime_info(creds, send_as_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail smimeInfo listed for %s (%.2fms)", send_as_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/settings/send-as/{send_as_email}/smime-info", response_model=GmailGenericResponse,
             summary="Insert an S/MIME certificate for a send-as alias (smimeInfo.insert)")
async def insert_smime_info(
    send_as_email: str,
    body: GmailSmimeInfoRequest,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.insert_smime_info(creds, send_as_email, body.payload, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail smimeInfo inserted for %s (%.2fms)", send_as_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/send-as/{send_as_email}/smime-info/{smime_info_id}",
            response_model=GmailGenericResponse,
            summary="Get a single S/MIME certificate (smimeInfo.get)")
async def get_smime_info(
    send_as_email: str,
    smime_info_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_smime_info(creds, send_as_email, smime_info_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail smimeInfo %s fetched (%.2fms)", smime_info_id, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/settings/send-as/{send_as_email}/smime-info/{smime_info_id}",
               response_model=GmailGenericResponse,
               summary="Delete an S/MIME certificate (smimeInfo.delete)")
async def delete_smime_info(
    send_as_email: str,
    smime_info_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_smime_info(creds, send_as_email, smime_info_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail smimeInfo %s deleted (%.2fms)", smime_info_id, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": smime_info_id})


@router.post("/settings/send-as/{send_as_email}/smime-info/{smime_info_id}/setDefault",
             response_model=GmailGenericResponse,
             summary="Set an S/MIME certificate as the default for a send-as alias (smimeInfo.setDefault)")
async def set_default_smime_info(
    send_as_email: str,
    smime_info_id: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.set_default_smime_info(creds, send_as_email, smime_info_id, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail smimeInfo %s set default (%.2fms)", smime_info_id, _elapsed_ms(start))
    return _ok(start, creds, {"default_set": smime_info_id})


@router.get("/settings/delegates", response_model=GmailGenericResponse,
            summary="List delegates")
async def list_delegates(
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.list_delegates(creds, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail delegates listed (%.2fms)", _elapsed_ms(start))
    return _ok(start, creds, data)


@router.get("/settings/delegates/{delegate_email}", response_model=GmailGenericResponse,
            summary="Get a delegate")
async def get_delegate(
    delegate_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        data = await service.get_delegate(creds, delegate_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail delegate %s fetched (%.2fms)", delegate_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.post("/settings/delegates", response_model=GmailGenericResponse,
             summary="Create a delegate")
async def create_delegate(
    body: Dict[str, str],
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    delegate_email = body.get("delegate_email", "")
    if not delegate_email:
        raise HTTPException(status_code=400, detail="delegate_email is required.")
    try:
        data = await service.create_delegate(creds, delegate_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail delegate %s created (%.2fms)", delegate_email, _elapsed_ms(start))
    return _ok(start, creds, data)


@router.delete("/settings/delegates/{delegate_email}", response_model=GmailGenericResponse,
               summary="Delete a delegate")
async def delete_delegate(
    delegate_email: str,
    creds: GmailCredentials = Depends(_credentials),
    service: GmailService = Depends(get_gmail_service),
    user_id: Optional[str] = None,
):
    start = time.perf_counter()
    try:
        await service.delete_delegate(creds, delegate_email, user_id=user_id or "me")
    except GmailAPIError as exc:
        raise _http_error(exc) from exc
    _logger.info("Gmail delegate %s deleted (%.2fms)", delegate_email, _elapsed_ms(start))
    return _ok(start, creds, {"deleted": delegate_email})