File size: 19,714 Bytes
097eaf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Response } from "express";
import { z } from "zod";
import { logger as _logger } from "../../lib/logger";
import { RequestWithAuth } from "./types";
import { getScrapeZDR } from "../../lib/zdr-helpers";
import { getMonitorDiffArtifact } from "../../lib/gcs-monitoring";
import {
  createMonitorSchema,
  listMonitorChecksQuerySchema,
  listMonitorsQuerySchema,
  monitorCheckDetailQuerySchema,
  updateMonitorSchema,
} from "../../services/monitoring/types";
import {
  createMonitor,
  createMonitorCheck,
  countMonitorCheckPages,
  deleteMonitor,
  estimateMonitorCreditsPerRun,
  getMonitor,
  getMonitorCheck,
  getMonitorForUpdate,
  listMonitorCheckPages,
  listMonitorChecks,
  listMonitors,
  updateMonitor,
} from "../../services/monitoring/store";
import { enqueueMonitorCheck } from "../../services/monitoring/scheduler";
import {
  estimateRunsPerMonth,
  validateMonitorCron,
} from "../../services/monitoring/cron";
import {
  getRemovedMonitorTargets,
  trackMonitorConfiguredInterest,
  trackMonitorDeactivatedInterest,
} from "../../services/monitoring/interest";
import {
  getLatestWebhookLog,
  getLatestWebhookLogsByJob,
  type WebhookLogRow,
} from "../../services/webhook/logs";
import { WebhookEvent } from "../../services/webhook";
import {
  confirmRecipientByToken,
  getMonitorNameById,
  listMonitorEmailRecipients,
  unsubscribeRecipientByToken,
} from "../../services/monitoring/email_recipients";
import { syncMonitorEmailRecipients } from "../../services/monitoring/email_recipients_sync";

const logger = _logger.child({ module: "monitor-controller" });

const monitorParamsSchema = z.strictObject({
  monitorId: z.uuid(),
});

const monitorCheckParamsSchema = monitorParamsSchema.extend({
  checkId: z.uuid(),
});

function rejectZdr(
  req: RequestWithAuth<any, any, any>,
  res: Response,
): boolean {
  if (getScrapeZDR(req.acuc?.flags) === "forced") {
    res.status(400).json({
      success: false,
      error:
        "Monitoring requires retained snapshots and diffs, and is not supported for zero data retention teams.",
    });
    return true;
  }
  return false;
}

function serializeMonitor(
  monitor: any,
  options?: {
    emailRecipientSubscriptions?: Array<{
      email: string;
      status: "pending" | "confirmed" | "unsubscribed";
      source: "team" | "opt_in" | "legacy";
      confirmationEmailSent?: boolean;
    }>;
  },
) {
  return {
    id: monitor.id,
    name: monitor.name,
    status: monitor.status,
    schedule: {
      cron: monitor.schedule_cron,
      timezone: monitor.schedule_timezone,
    },
    nextRunAt: monitor.next_run_at,
    lastRunAt: monitor.last_run_at,
    currentCheckId: monitor.current_check_id,
    targets: monitor.targets,
    webhook: monitor.webhook,
    notification: monitor.notification,
    ...(options?.emailRecipientSubscriptions !== undefined
      ? { emailRecipientSubscriptions: options.emailRecipientSubscriptions }
      : {}),
    retentionDays: monitor.retention_days,
    estimatedCreditsPerMonth: monitor.estimated_credits_per_month,
    lastCheckSummary: monitor.last_check_summary,
    goal: monitor.goal ?? null,
    judgeEnabled: Boolean(monitor.judge_enabled),
    createdAt: monitor.created_at,
    updatedAt: monitor.updated_at,
  };
}

async function loadEmailRecipientSubscriptions(monitorId: string) {
  const rows = await listMonitorEmailRecipients(monitorId);
  return rows.map(r => ({
    email: r.email,
    status: r.status,
    source: r.source,
    confirmationEmailSent: r.confirmation_sent_at !== null,
  }));
}

function overlayWebhookLog<T extends { notificationStatus: any }>(
  serialized: T,
  log: WebhookLogRow | null,
): T {
  if (!log) return serialized;
  const notificationStatus =
    serialized.notificationStatus &&
    typeof serialized.notificationStatus === "object"
      ? serialized.notificationStatus
      : {};
  const existing =
    notificationStatus.webhook && typeof notificationStatus.webhook === "object"
      ? notificationStatus.webhook
      : {};
  return {
    ...serialized,
    notificationStatus: {
      ...notificationStatus,
      webhook: {
        ...existing,
        attempted: true,
        success: log.success === true,
        delivered: log.success === true,
        queued: false,
        statusCode: log.status_code ?? undefined,
        error: log.error ?? undefined,
        deliveredAt: log.created_at,
      },
    },
  };
}

function serializeCheck(check: any) {
  return {
    id: check.id,
    monitorId: check.monitor_id,
    status: check.status,
    trigger: check.trigger,
    scheduledFor: check.scheduled_for,
    startedAt: check.started_at,
    finishedAt: check.finished_at,
    estimatedCredits: check.estimated_credits,
    reservedCredits: check.reserved_credits,
    actualCredits: check.actual_credits,
    billingStatus: check.billing_status,
    summary: {
      totalPages: check.total_pages,
      same: check.same_count,
      changed: check.changed_count,
      new: check.new_count,
      removed: check.removed_count,
      error: check.error_count,
    },
    targetResults: check.target_results,
    notificationStatus: check.notification_status,
    error: check.error,
    createdAt: check.created_at,
    updatedAt: check.updated_at,
  };
}

export async function createMonitorController(
  req: RequestWithAuth<{}, any, unknown>,
  res: Response,
) {
  if (rejectZdr(req, res)) return;

  const input = createMonitorSchema.parse(req.body);
  let schedule;
  try {
    schedule = validateMonitorCron(
      input.schedule.cron,
      input.schedule.timezone,
    );
  } catch (error) {
    return res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : String(error),
    });
  }
  const monitor = await createMonitor({
    teamId: req.auth.team_id,
    input,
    nextRunAt: schedule.nextRunAt,
    intervalMs: schedule.intervalMs,
  });

  trackMonitorConfiguredInterest({
    monitor,
    intervalMs: schedule.intervalMs,
  }).catch(error =>
    logger.warn("Failed to track monitor target interest", {
      error,
      monitorId: monitor.id,
      eventType: "configured",
    }),
  );

  const sync = await syncMonitorEmailRecipients({ monitor }).catch(error => {
    logger.warn("Failed to sync monitor email recipients on create", {
      error,
      monitorId: monitor.id,
    });
    return { recipients: [] };
  });

  res.status(200).json({
    success: true,
    data: serializeMonitor(monitor, {
      emailRecipientSubscriptions: sync.recipients,
    }),
  });
}

export async function listMonitorsController(
  req: RequestWithAuth<{}, any, unknown>,
  res: Response,
) {
  const query = listMonitorsQuerySchema.parse(req.query);
  const monitors = await listMonitors({
    teamId: req.auth.team_id,
    limit: query.limit,
    offset: query.offset,
  });

  res.status(200).json({
    success: true,
    data: monitors.map(monitor => serializeMonitor(monitor)),
  });
}

export async function getMonitorController(
  req: RequestWithAuth<{ monitorId: string }, any, unknown>,
  res: Response,
) {
  const { monitorId } = monitorParamsSchema.parse(req.params);
  const monitor = await getMonitor(req.auth.team_id, monitorId);
  if (!monitor) {
    return res.status(404).json({ success: false, error: "Monitor not found" });
  }

  const subscriptions = await loadEmailRecipientSubscriptions(monitorId).catch(
    error => {
      logger.warn("Failed to load email recipient subscriptions", {
        error,
        monitorId,
      });
      return [];
    },
  );

  res.status(200).json({
    success: true,
    data: serializeMonitor(monitor, {
      emailRecipientSubscriptions: subscriptions,
    }),
  });
}

export async function updateMonitorController(
  req: RequestWithAuth<{ monitorId: string }, any, unknown>,
  res: Response,
) {
  if (rejectZdr(req, res)) return;

  const { monitorId } = monitorParamsSchema.parse(req.params);
  const existing = await getMonitorForUpdate(req.auth.team_id, monitorId);
  if (!existing) {
    return res.status(404).json({ success: false, error: "Monitor not found" });
  }

  const input = updateMonitorSchema.parse(req.body);
  const cron = input.schedule?.cron ?? existing.schedule_cron;
  const timezone = input.schedule?.timezone ?? existing.schedule_timezone;
  let schedule;
  try {
    schedule = validateMonitorCron(cron, timezone);
  } catch (error) {
    return res.status(400).json({
      success: false,
      error: error instanceof Error ? error.message : String(error),
    });
  }
  const monitor = await updateMonitor({
    teamId: req.auth.team_id,
    monitorId,
    input,
    nextRunAt: input.schedule ? schedule.nextRunAt : undefined,
    intervalMs:
      input.schedule || input.targets ? schedule.intervalMs : undefined,
  });
  if (!monitor) {
    return res.status(404).json({ success: false, error: "Monitor not found" });
  }

  const interestTracking: Promise<void>[] = [];
  const removedTargets = input.targets
    ? getRemovedMonitorTargets({ before: existing, after: monitor })
    : [];
  if (removedTargets.length > 0) {
    interestTracking.push(
      trackMonitorDeactivatedInterest({
        monitor: existing,
        targets: removedTargets,
      }),
    );
  }
  if (
    monitor.status === "paused" &&
    (input.status === "paused" || input.schedule || input.targets)
  ) {
    interestTracking.push(
      trackMonitorDeactivatedInterest({
        monitor,
        intervalMs: schedule.intervalMs,
      }),
    );
  } else if (input.schedule || input.targets || input.status === "active") {
    interestTracking.push(
      trackMonitorConfiguredInterest({
        monitor,
        intervalMs: schedule.intervalMs,
      }),
    );
  }
  Promise.all(interestTracking).catch(error =>
    logger.warn("Failed to track monitor target interest", {
      error,
      monitorId: monitor.id,
      eventType: "update",
    }),
  );

  // Only re-sync when notification config actually changed.
  let subscriptions: Awaited<
    ReturnType<typeof loadEmailRecipientSubscriptions>
  > = [];
  if (input.notification !== undefined) {
    const sync = await syncMonitorEmailRecipients({ monitor }).catch(error => {
      logger.warn("Failed to sync monitor email recipients on update", {
        error,
        monitorId: monitor.id,
      });
      return { recipients: [] };
    });
    subscriptions = sync.recipients;
  } else {
    subscriptions = await loadEmailRecipientSubscriptions(monitor.id);
  }

  res.status(200).json({
    success: true,
    data: serializeMonitor(monitor, {
      emailRecipientSubscriptions: subscriptions,
    }),
  });
}

export async function deleteMonitorController(
  req: RequestWithAuth<{ monitorId: string }, any, unknown>,
  res: Response,
) {
  const { monitorId } = monitorParamsSchema.parse(req.params);
  const existing = await getMonitorForUpdate(req.auth.team_id, monitorId);
  if (!existing) {
    return res.status(404).json({ success: false, error: "Monitor not found" });
  }

  const deleted = await deleteMonitor({
    teamId: req.auth.team_id,
    monitorId,
  });
  if (!deleted) {
    return res.status(404).json({ success: false, error: "Monitor not found" });
  }

  trackMonitorDeactivatedInterest({
    monitor: { ...existing, status: "deleted" },
  }).catch(error =>
    logger.warn("Failed to track monitor target interest", {
      error,
      monitorId,
      eventType: "deactivated",
    }),
  );

  res.status(200).json({ success: true });
}

export async function runMonitorController(
  req: RequestWithAuth<{ monitorId: string }, any, unknown>,
  res: Response,
) {
  if (rejectZdr(req, res)) return;

  const { monitorId } = monitorParamsSchema.parse(req.params);
  const monitor = await getMonitorForUpdate(req.auth.team_id, monitorId);
  if (!monitor) {
    return res.status(404).json({ success: false, error: "Monitor not found" });
  }
  if (monitor.current_check_id) {
    return res.status(409).json({
      success: false,
      error: "Monitor check is already running.",
      checkId: monitor.current_check_id,
    });
  }

  const check = await createMonitorCheck({
    monitor,
    trigger: "manual",
  });
  await enqueueMonitorCheck({
    monitorId: monitor.id,
    checkId: check.id,
    teamId: monitor.team_id,
  });

  res.status(200).json({
    success: true,
    id: check.id,
    data: serializeCheck(check),
  });
}

export async function listMonitorChecksController(
  req: RequestWithAuth<{ monitorId: string }, any, unknown>,
  res: Response,
) {
  const { monitorId } = monitorParamsSchema.parse(req.params);
  const monitor = await getMonitor(req.auth.team_id, monitorId);
  if (!monitor) {
    return res.status(404).json({ success: false, error: "Monitor not found" });
  }

  const query = listMonitorChecksQuerySchema.parse(req.query);
  const checks = await listMonitorChecks({
    teamId: req.auth.team_id,
    monitorId,
    limit: query.limit,
    offset: query.offset,
    status: query.status,
  });

  const webhookLogs = await getLatestWebhookLogsByJob({
    jobIds: checks.map(c => c.id),
    event: WebhookEvent.MONITOR_CHECK_COMPLETED,
  });

  res.status(200).json({
    success: true,
    data: checks.map(check =>
      overlayWebhookLog(
        serializeCheck(check),
        webhookLogs.get(check.id) ?? null,
      ),
    ),
  });
}

export async function getMonitorCheckController(
  req: RequestWithAuth<{ monitorId: string; checkId: string }, any, unknown>,
  res: Response,
) {
  const { monitorId, checkId } = monitorCheckParamsSchema.parse(req.params);
  const query = monitorCheckDetailQuerySchema.parse(req.query);
  const skip = query.skip;
  const check = await getMonitorCheck(req.auth.team_id, monitorId, checkId);
  if (!check) {
    return res.status(404).json({ success: false, error: "Check not found" });
  }

  const [pages, totalPagesForFilter, webhookLog] = await Promise.all([
    listMonitorCheckPages({
      teamId: req.auth.team_id,
      monitorId,
      checkId,
      limit: query.limit,
      skip,
      status: query.status,
    }),
    countMonitorCheckPages({
      checkId,
      status: query.status,
    }),
    getLatestWebhookLog({
      jobId: checkId,
      event: WebhookEvent.MONITOR_CHECK_COMPLETED,
    }),
  ]);

  const pagesWithDiffs = await Promise.all(
    pages.map(async page => {
      const artifact = await getMonitorDiffArtifact(page.diff_gcs_key);
      const base = {
        id: page.id,
        targetId: page.target_id,
        url: page.url,
        status: page.status,
        previousScrapeId: page.previous_scrape_id,
        currentScrapeId: page.current_scrape_id,
        statusCode: page.status_code,
        error: page.error,
        metadata: page.metadata,
        judgment: page.judgment ?? null,
        createdAt: page.created_at,
      };
      if (!artifact) {
        return { ...base, diff: null };
      }
      if (artifact.kind === "json") {
        return {
          ...base,
          diff: {
            json: artifact.json,
            ...(artifact.markdown ? { text: artifact.markdown.text } : {}),
          },
          snapshot: { json: artifact.snapshot },
        };
      }
      return {
        ...base,
        diff: { text: artifact.text, json: artifact.json },
      };
    }),
  );
  const nextSkip = skip + pagesWithDiffs.length;
  const next = (() => {
    if (totalPagesForFilter <= nextSkip) return undefined;
    const url = new URL(
      `/v2/monitor/${monitorId}/checks/${checkId}`,
      `${req.protocol}://${req.get("host")}`,
    );
    url.searchParams.set("skip", String(nextSkip));
    url.searchParams.set("limit", String(query.limit));
    if (query.status) url.searchParams.set("status", query.status);
    return url.toString();
  })();

  res.status(200).json({
    success: true,
    next,
    data: {
      ...overlayWebhookLog(serializeCheck(check), webhookLog),
      pages: pagesWithDiffs,
      next,
    },
  });
}

// Unauthenticated POST endpoints — the token is the credential. Backs the
// firecrawl-web confirm/unsubscribe pages; POST-only so passive GET scanners
// can't consume tokens against the dashboard URL.

const emailActionBodySchema = z.object({
  // 32-byte base64url is 43 chars; range leaves room for future formats.
  token: z.string().min(16).max(64),
});

type EmailActionResponse =
  | {
      success: true;
      result: "confirmed" | "already_confirmed" | "unsubscribed" | "already_unsubscribed";
      email: string;
      monitorName: string | null;
    }
  | {
      success: false;
      error: "invalid_token" | "not_found" | "internal_error";
    };


function parseTokenFromRequest(req: { body?: unknown }): string | null {
  const candidate =
    req.body && typeof req.body === "object"
      ? (req.body as { token?: unknown }).token
      : null;
  const parsed = emailActionBodySchema.safeParse({ token: candidate });
  return parsed.success ? parsed.data.token : null;
}

export async function confirmMonitorEmailController(
  req: { body?: unknown },
  res: Response,
) {
  const token = parseTokenFromRequest(req);
  if (!token) {
    const body: EmailActionResponse = {
      success: false,
      error: "invalid_token",
    };
    return res.status(400).json(body);
  }

  try {
    const row = await confirmRecipientByToken(token);
    if (!row) {
      const body: EmailActionResponse = {
        success: false,
        error: "not_found",
      };
      return res.status(404).json(body);
    }

    const monitorName = await getMonitorNameById(row.monitor_id);

    // Heuristic: if confirmed_at is older than 5s, this call was a no-op
    // (already confirmed). Used only to flavor the rendered page.
    let result: "confirmed" | "already_confirmed" | "already_unsubscribed";
    if (row.status === "unsubscribed") {
      result = "already_unsubscribed";
    } else if (
      row.confirmed_at !== null &&
      new Date().getTime() - new Date(row.confirmed_at).getTime() > 5_000
    ) {
      result = "already_confirmed";
    } else {
      result = "confirmed";
    }

    const body: EmailActionResponse = {
      success: true,
      result,
      email: row.email,
      monitorName,
    };
    return res.status(200).json(body);
  } catch (error) {
    logger.error("Failed to confirm monitor email recipient", { error });
    const body: EmailActionResponse = {
      success: false,
      error: "internal_error",
    };
    return res.status(500).json(body);
  }
}

export async function unsubscribeMonitorEmailController(
  req: { body?: unknown },
  res: Response,
) {
  const token = parseTokenFromRequest(req);
  if (!token) {
    const body: EmailActionResponse = {
      success: false,
      error: "invalid_token",
    };
    return res.status(400).json(body);
  }

  try {
    const row = await unsubscribeRecipientByToken(token);
    if (!row) {
      const body: EmailActionResponse = {
        success: false,
        error: "not_found",
      };
      return res.status(404).json(body);
    }

    const monitorName = await getMonitorNameById(row.monitor_id);

    const result: "unsubscribed" | "already_unsubscribed" =
      row.unsubscribed_at !== null &&
      new Date().getTime() - new Date(row.unsubscribed_at).getTime() > 5_000
        ? "already_unsubscribed"
        : "unsubscribed";

    const body: EmailActionResponse = {
      success: true,
      result,
      email: row.email,
      monitorName,
    };
    return res.status(200).json(body);
  } catch (error) {
    logger.error("Failed to unsubscribe monitor email recipient", { error });
    const body: EmailActionResponse = {
      success: false,
      error: "internal_error",
    };
    return res.status(500).json(body);
  }
}