summaryrefslogtreecommitdiff
path: root/src/routes/parent.ts
blob: db7206d2b5c48338a885d718f5048268cde242db (plain)
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
import express from "express";
import { authParent } from "../middleware/auth";
import { db } from "../db/db";
import { deviceConfig, linkedDevices, users, alerts } from "../db/schema";
import { eq, and, desc } from "drizzle-orm";
import { isValidPushToken } from "../notifications/push";
import { logger } from "../lib/pino";
import { z } from "zod";

/** Validates email verification code from user input */
const VerifyEmailSchema = z.object({
  code: z.string().min(1, "Verification code cannot be empty"),
});

/** Validates device ID from URL parameters */
const DeviceIdParamSchema = z.object({
  deviceId: z.string().regex(/^\d+$/, "Device ID must be numeric"),
});

/** Validates control settings updates with allowed keys and boolean values */
const ControlsUpdateSchema = z.object({
  key: z.enum([
    "disable_buddy",
    "adult_sites",
    "new_people",
    "block_strangers",
    "notify_dangerous_messages",
    "notify_new_contact_added",
    "family_link_anti_circumvention",
  ]),
  value: z.boolean(),
});

/** Validates device nickname changes */
const DeviceRenameSchema = z.object({
  name: z.string().min(1, "Name cannot be empty").max(255, "Name too long"),
});

/** Validates push notification token format */
const PushTokenSchema = z.object({
  token: z.string().min(1, "Token cannot be empty"),
});

function createParentRouter(
  onlineDevices: Map<number, { connectedAt: number }>,
) {
  const router: express.Router = express.Router();

  /**
   * Converts a Unix timestamp to a human-readable relative time string.
   * Returns things like "Just now", "5m ago", "2d ago", etc.
   */
  const formatLastOnline = (timestamp: number | null | undefined): string => {
    if (!timestamp) return "Never";
    const lastOnlineDate = new Date(timestamp * 1000);
    const now = new Date();
    const diffMs = now.getTime() - lastOnlineDate.getTime();
    const diffSecs = Math.floor(diffMs / 1000);
    const diffMins = Math.floor(diffSecs / 60);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffSecs < 60) return "Just now";
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    if (diffDays < 7) return `${diffDays}d ago`;
    return lastOnlineDate.toLocaleDateString();
  };

  router.post("/parent/verifyemail", authParent, async (req, res) => {
    const parentId = req.user!.id;

    const parsed = VerifyEmailSchema.safeParse(req.body);
    if (!parsed.success) {
      logger.warn(
        { parentId, error: parsed.error },
        "Invalid verification code in request",
      );
      return res.status(400).json({
        success: false,
        reason: parsed.error.issues[0]?.message || "Invalid verification code",
      });
    }

    const { code } = parsed.data;

    try {
      const user = await db
        .select()
        .from(users)
        .where(eq(users.id, parentId))
        .limit(1);

      if (user.length === 0) {
        logger.warn({ parentId }, "User not found for email verification");
        return res
          .status(404)
          .json({ success: false, reason: "User not found" });
      }

      const storedCode = user[0]!.emailCode;
      if (!storedCode) {
        logger.warn({ parentId }, "No verification code set for user");
        return res
          .status(400)
          .json({ success: false, reason: "No verification code set" });
      }

      if (storedCode !== code) {
        logger.warn({ parentId }, "Incorrect email verification code");
        return res
          .status(400)
          .json({ success: false, reason: "Incorrect verification code" });
      }

      try {
        await db
          .update(users)
          .set({ emailVerified: true })
          .where(eq(users.id, parentId));
        logger.info({ parentId }, "Email verified successfully");
        return res.json({ success: true });
      } catch (updateError) {
        logger.error(
          { error: updateError, parentId },
          "Database error updating email verification",
        );
        throw updateError;
      }
    } catch (e) {
      logger.error({ error: e, parentId }, "Failed to verify email");
      return res
        .status(500)
        .json({ success: false, reason: "Failed to verify email" });
    }
  });

  router.get("/parent/profile", authParent, async (req, res) => {
    const parentId = req.user!.id;

    try {
      const user = await db
        .select({
          email: users.email,
          emailVerified: users.emailVerified,
        })
        .from(users)
        .where(eq(users.id, parentId))
        .limit(1);

      if (user.length === 0) {
        logger.warn({ parentId }, "User not found for profile request");
        return res
          .status(404)
          .json({ success: false, reason: "User not found" });
      }

      logger.debug({ parentId }, "Profile retrieved successfully");
      return res.json({
        success: true,
        profile: {
          email: user[0]!.email,
          emailVerified: user[0]!.emailVerified ?? false,
        },
      });
    } catch (e) {
      logger.error({ error: e, parentId }, "Failed to get profile");
      return res
        .status(500)
        .json({ success: false, reason: "Failed to get profile" });
    }
  });

  router.get("/parent/devices", authParent, async (req, res) => {
    const parentId = req.user!.id;

    if (!parentId || typeof parentId !== "number") {
      logger.error({ parentId }, "Invalid parent ID in devices request");
      res.status(400).json({
        success: false,
        reason: "Invalid parent ID",
      });
      return;
    }

    try {
      const devices = await db
        .select()
        .from(linkedDevices)
        .where(eq(linkedDevices.parentId, parentId));

      logger.debug(
        { parentId, deviceCount: devices.length },
        "Retrieved parent devices",
      );

      res.json({
        success: true,
        devices: devices.map((d) => ({
          id: d.id.toString(),
          name: d.nickname,
          status: onlineDevices.has(d.id) ? "online" : "offline",
          lastCheck: formatLastOnline(d.lastOnline),
        })),
      });
    } catch (e) {
      logger.error({ error: e, parentId }, "Failed to get devices");
      res.status(500).json({
        success: false,
        reason: "Failed to get devices",
      });
    }
  });

  router.get("/parent/controls/:deviceId", authParent, async (req, res) => {
    const parentId = req.user!.id;

    const paramsParsed = DeviceIdParamSchema.safeParse(req.params);
    if (!paramsParsed.success) {
      logger.warn(
        { deviceId: req.params.deviceId, parentId, error: paramsParsed.error },
        "Invalid device ID in controls request",
      );
      res.status(400).json({
        success: false,
        reason: "Invalid device ID",
      });
      return;
    }

    const deviceId = parseInt(paramsParsed.data.deviceId);

    try {
      // Verify the device belongs to this parent
      let device;
      try {
        device = await db
          .select()
          .from(linkedDevices)
          .where(
            and(
              eq(linkedDevices.id, deviceId),
              eq(linkedDevices.parentId, parentId),
            ),
          )
          .limit(1);
      } catch (dbError) {
        logger.error(
          { error: dbError, deviceId, parentId },
          "Database error verifying device ownership",
        );
        throw dbError;
      }

      if (device.length === 0) {
        logger.warn(
          { deviceId, parentId },
          "Device not found or does not belong to parent",
        );
        res.status(404).json({
          success: false,
          reason: "Device not found",
        });
        return;
      }

      // Get or create config for this device
      let config;
      try {
        config = await db
          .select()
          .from(deviceConfig)
          .where(eq(deviceConfig.deviceId, deviceId))
          .limit(1);
      } catch (dbError) {
        logger.error(
          { error: dbError, deviceId },
          "Database error fetching device config",
        );
        throw dbError;
      }

      if (config.length === 0) {
        // Create default config for new device
        try {
          const newConfig = await db
            .insert(deviceConfig)
            .values({ deviceId })
            .returning();
          config = newConfig;
          logger.info({ deviceId }, "Created default config for device");
        } catch (insertError) {
          logger.error(
            { error: insertError, deviceId },
            "Failed to create default device config",
          );
          throw insertError;
        }
      }

      const cfg = config[0];
      if (!cfg) {
        logger.error({ deviceId }, "Config is unexpectedly undefined");
        res.status(500).json({
          success: false,
          reason: "Failed to get controls",
        });
        return;
      }

      logger.debug(
        { deviceId, parentId },
        "Device controls retrieved successfully",
      );

      res.json({
        success: true,
        safetyControls: [
          {
            key: "disable_buddy",
            title: "Disable Buddy",
            description: "Temporarily disable Buddy",
            defaultValue: cfg.disableBuddy,
          },
          {
            key: "adult_sites",
            title: "Adult sites",
            description: "Block adult websites.",
            defaultValue: cfg.blockAdultSites,
          },
          {
            key: "family_link_anti_circumvention",
            title: "Anti-Circumvention",
            description: "Prevent disabling of Family Link protections.",
            defaultValue: cfg.familyLinkAntiCircumvention,
          },
          {
            key: "new_people",
            title: "New contact alerts",
            description: "Get notified when your child chats with someone new.",
            defaultValue: cfg.newContactAlerts,
          },
          {
            key: "block_strangers",
            title: "Block communications with strangers",
            description: "Block or scan communications with strangers.",
            defaultValue: cfg.blockStrangers,
          },
          {
            key: "notify_dangerous_messages",
            title: "Dangerous messages notifications",
            description: "Notify when messages are potentially dangerous.",
            defaultValue: cfg.notifyDangerousMessages,
          },
          {
            key: "notify_new_contact_added",
            title: "New contact added notifications",
            description: "Notify when a new contact is added.",
            defaultValue: cfg.notifyNewContactAdded,
          },
        ],
      });
    } catch (e) {
      logger.error({ error: e, deviceId, parentId }, "Failed to get controls");
      res.status(500).json({
        success: false,
        reason: "Failed to get controls",
      });
    }
  });

  // Update a safety control for a specific device
  router.post("/parent/controls/:deviceId", authParent, async (req, res) => {
    const parentId = req.user!.id;

    const paramsParsed = DeviceIdParamSchema.safeParse(req.params);
    if (!paramsParsed.success) {
      logger.warn(
        { deviceId: req.params.deviceId, parentId, error: paramsParsed.error },
        "Invalid device ID in controls update",
      );
      res.status(400).json({
        success: false,
        reason: "Invalid device ID",
      });
      return;
    }

    const bodyParsed = ControlsUpdateSchema.safeParse(req.body);
    if (!bodyParsed.success) {
      logger.warn(
        { body: req.body, parentId, error: bodyParsed.error },
        "Invalid request body for controls update",
      );
      res.status(400).json({
        success: false,
        reason: bodyParsed.error.issues[0]?.message || "Invalid request body",
      });
      return;
    }

    const deviceId = parseInt(paramsParsed.data.deviceId);
    const { key, value } = bodyParsed.data;

    // Map frontend keys to database columns
    const keyMap: Record<string, keyof typeof deviceConfig.$inferSelect> = {
      disable_buddy: "disableBuddy",
      adult_sites: "blockAdultSites",
      new_people: "newContactAlerts",
      block_strangers: "blockStrangers",
      notify_dangerous_messages: "notifyDangerousMessages",
      notify_new_contact_added: "notifyNewContactAdded",
      family_link_anti_circumvention: "familyLinkAntiCircumvention",
    };

    const dbKey = keyMap[key];
    if (!dbKey) {
      logger.warn({ key, deviceId, parentId }, "Unknown control key");
      res.status(400).json({
        success: false,
        reason: "Unknown control key",
      });
      return;
    }

    try {
      // Verify the device belongs to this parent
      let device;
      try {
        device = await db
          .select()
          .from(linkedDevices)
          .where(
            and(
              eq(linkedDevices.id, deviceId),
              eq(linkedDevices.parentId, parentId),
            ),
          )
          .limit(1);
      } catch (dbError) {
        logger.error(
          { error: dbError, deviceId, parentId },
          "Database error verifying device ownership for control update",
        );
        throw dbError;
      }

      if (device.length === 0) {
        logger.warn(
          { deviceId, parentId },
          "Device not found for control update",
        );
        res.status(404).json({
          success: false,
          reason: "Device not found",
        });
        return;
      }

      // Ensure config exists
      let existingConfig;
      try {
        existingConfig = await db
          .select()
          .from(deviceConfig)
          .where(eq(deviceConfig.deviceId, deviceId))
          .limit(1);
      } catch (dbError) {
        logger.error(
          { error: dbError, deviceId },
          "Database error fetching config for update",
        );
        throw dbError;
      }

      if (existingConfig.length === 0) {
        try {
          await db.insert(deviceConfig).values({ deviceId });
          logger.info(
            { deviceId },
            "Created default config for control update",
          );
        } catch (insertError) {
          logger.error(
            { error: insertError, deviceId },
            "Failed to create config for control update",
          );
          throw insertError;
        }
      }

      // Update the specific field
      try {
        await db
          .update(deviceConfig)
          .set({ [dbKey]: value })
          .where(eq(deviceConfig.deviceId, deviceId));
        logger.info(
          { deviceId, key, value, dbKey },
          "Device control updated successfully",
        );
      } catch (updateError) {
        logger.error(
          { error: updateError, deviceId, key, value },
          "Database error updating control",
        );
        throw updateError;
      }

      res.json({
        success: true,
      });
    } catch (e) {
      logger.error(
        { error: e, deviceId, parentId, key },
        "Failed to update control",
      );
      res.status(500).json({
        success: false,
        reason: "Failed to update control",
      });
    }
  });

  // Rename a device
  router.post(
    "/parent/device/:deviceId/rename",
    authParent,
    async (req, res) => {
      const parentId = req.user!.id;

      const paramsParsed = DeviceIdParamSchema.safeParse(req.params);
      if (!paramsParsed.success) {
        logger.warn(
          {
            deviceId: req.params.deviceId,
            parentId,
            error: paramsParsed.error,
          },
          "Invalid device ID in rename request",
        );
        return res
          .status(400)
          .json({ success: false, reason: "Invalid device ID" });
      }

      const bodyParsed = DeviceRenameSchema.safeParse(req.body);
      if (!bodyParsed.success) {
        logger.warn(
          { body: req.body, parentId, error: bodyParsed.error },
          "Invalid name in rename request",
        );
        return res.status(400).json({
          success: false,
          reason: bodyParsed.error.issues[0]?.message || "Invalid name",
        });
      }

      const deviceId = parseInt(paramsParsed.data.deviceId);
      const { name } = bodyParsed.data;

      try {
        // Verify the device belongs to this parent
        let device;
        try {
          device = await db
            .select()
            .from(linkedDevices)
            .where(
              and(
                eq(linkedDevices.id, deviceId),
                eq(linkedDevices.parentId, parentId),
              ),
            )
            .limit(1);
        } catch (dbError) {
          logger.error(
            { error: dbError, deviceId, parentId },
            "Database error verifying device ownership for rename",
          );
          throw dbError;
        }

        if (device.length === 0) {
          logger.warn({ deviceId, parentId }, "Device not found for rename");
          return res
            .status(404)
            .json({ success: false, reason: "Device not found" });
        }

        // Update the device name
        try {
          await db
            .update(linkedDevices)
            .set({ nickname: name })
            .where(eq(linkedDevices.id, deviceId));
          logger.info(
            { deviceId, oldName: device[0]!.nickname, newName: name },
            "Device renamed successfully",
          );
        } catch (updateError) {
          logger.error(
            { error: updateError, deviceId, name },
            "Database error renaming device",
          );
          throw updateError;
        }

        res.json({ success: true });
      } catch (e) {
        logger.error(
          { error: e, deviceId, parentId },
          "Failed to rename device",
        );
        res
          .status(500)
          .json({ success: false, reason: "Failed to rename device" });
      }
    },
  );

  // Get home dashboard data
  router.get("/parent/home", authParent, async (req, res) => {
    const parentId = req.user!.id;

    try {
      // Get linked devices count
      let devices;
      try {
        devices = await db
          .select()
          .from(linkedDevices)
          .where(eq(linkedDevices.parentId, parentId));
      } catch (dbError) {
        logger.error(
          { error: dbError, parentId },
          "Database error fetching devices for home dashboard",
        );
        throw dbError;
      }

      // Check if any device is online
      const anyDeviceOnline = devices.some((d) => onlineDevices.has(d.id));

      logger.debug(
        { parentId, deviceCount: devices.length, anyDeviceOnline },
        "Home dashboard data retrieved",
      );

      // TODO: Add alerts table and query real alert stats
      res.json({
        success: true,
        overallStatus: "all_clear",
        deviceOnline: anyDeviceOnline,
        alertStats: {
          last24Hours: 0,
          thisWeekReviewed: 0,
        },
      });
    } catch (e) {
      logger.error({ error: e, parentId }, "Failed to get home data");
      res.status(500).json({
        success: false,
        reason: "Failed to get home data",
      });
    }
  });

  // Get home dashboard data for a specific device
  router.get("/parent/home/:deviceId", authParent, async (req, res) => {
    const parentId = req.user!.id;

    const paramsParsed = DeviceIdParamSchema.safeParse(req.params);
    if (!paramsParsed.success) {
      logger.warn(
        { deviceId: req.params.deviceId, parentId, error: paramsParsed.error },
        "Invalid device ID in home request",
      );
      res.status(400).json({
        success: false,
        reason: "Invalid device ID",
      });
      return;
    }

    const deviceId = parseInt(paramsParsed.data.deviceId);

    try {
      // Verify the device belongs to this parent
      let device;
      try {
        device = await db
          .select()
          .from(linkedDevices)
          .where(
            and(
              eq(linkedDevices.id, deviceId),
              eq(linkedDevices.parentId, parentId),
            ),
          )
          .limit(1);
      } catch (dbError) {
        logger.error(
          { error: dbError, deviceId, parentId },
          "Database error fetching device for home data",
        );
        throw dbError;
      }

      if (device.length === 0) {
        logger.warn({ deviceId, parentId }, "Device not found for home data");
        res.status(404).json({
          success: false,
          reason: "Device not found",
        });
        return;
      }

      // Check if this device is online using in-memory tracking
      const isDeviceOnline = onlineDevices.has(deviceId);

      logger.debug(
        { deviceId, parentId, isDeviceOnline },
        "Device home data retrieved",
      );

      // TODO: Add alerts table and query real alert stats for this device
      res.json({
        success: true,
        overallStatus: "all_clear",
        deviceOnline: isDeviceOnline,
        alertStats: {
          last24Hours: 0,
          thisWeekReviewed: 0,
        },
      });
    } catch (e) {
      logger.error(
        { error: e, deviceId, parentId },
        "Failed to get device home data",
      );
      res.status(500).json({
        success: false,
        reason: "Failed to get home data",
      });
    }
  });

  // Get activity data
  router.get("/parent/activity", authParent, async (req, res) => {
    // TODO: Implement real activity tracking
    res.json({
      success: true,
      period: "Last 7 days",
      metrics: [
        {
          id: "messaging",
          icon: "chatbubbles",
          title: "Messaging activity",
          description: "About the same as usual",
          level: "Normal",
        },
        {
          id: "new_people",
          icon: "people",
          title: "New people",
          description: "No new contacts",
          level: "Low",
        },
        {
          id: "late_night",
          icon: "time",
          title: "Late-night use",
          description: "No late night activity",
          level: "Normal",
        },
      ],
    });
  });

  // Register push notification token
  router.post("/parent/push-token", authParent, async (req, res) => {
    const parentId = req.user!.id;

    const parsed = PushTokenSchema.safeParse(req.body);
    if (!parsed.success) {
      logger.warn(
        { parentId, error: parsed.error },
        "Invalid push token in registration request",
      );
      res.status(400).json({
        success: false,
        reason: parsed.error.issues[0]?.message || "Invalid push token",
      });
      return;
    }

    const { token } = parsed.data;

    // Validate Expo push token format
    if (!isValidPushToken(token)) {
      logger.warn({ parentId, token }, "Invalid Expo push token format");
      res.status(400).json({
        success: false,
        reason: "Invalid Expo push token format",
      });
      return;
    }

    try {
      // Get current tokens
      let user;
      try {
        user = await db
          .select({ pushTokens: users.pushTokens })
          .from(users)
          .where(eq(users.id, parentId))
          .limit(1);
      } catch (dbError) {
        logger.error(
          { error: dbError, parentId },
          "Database error fetching user for push token",
        );
        throw dbError;
      }

      if (user.length === 0) {
        logger.error(
          { parentId },
          "User not found for push token registration",
        );
        res.status(404).json({
          success: false,
          reason: "User not found",
        });
        return;
      }

      const currentTokens = user[0]!.pushTokens || [];

      // Only add if not already present
      if (!currentTokens.includes(token)) {
        const updatedTokens = [...currentTokens, token];
        try {
          await db
            .update(users)
            .set({ pushTokens: updatedTokens })
            .where(eq(users.id, parentId));
          logger.info(
            { parentId, tokenCount: updatedTokens.length },
            "Push token registered successfully",
          );
        } catch (updateError) {
          logger.error(
            { error: updateError, parentId },
            "Database error updating push tokens",
          );
          throw updateError;
        }
      } else {
        logger.debug({ parentId }, "Push token already registered");
      }

      res.json({ success: true });
    } catch (e) {
      logger.error({ error: e, parentId }, "Failed to save push token");
      res.status(500).json({
        success: false,
        reason: "Failed to save push token",
      });
    }
  });

  // Remove push notification token
  router.delete("/parent/push-token", authParent, async (req, res) => {
    const parentId = req.user!.id;

    const parsed = PushTokenSchema.safeParse(req.body);
    if (!parsed.success) {
      logger.warn(
        { parentId, error: parsed.error },
        "Invalid push token in removal request",
      );
      res.status(400).json({
        success: false,
        reason: parsed.error.issues[0]?.message || "Invalid push token",
      });
      return;
    }

    const { token } = parsed.data;

    try {
      // Get current tokens
      let user;
      try {
        user = await db
          .select({ pushTokens: users.pushTokens })
          .from(users)
          .where(eq(users.id, parentId))
          .limit(1);
      } catch (dbError) {
        logger.error(
          { error: dbError, parentId },
          "Database error fetching user for push token removal",
        );
        throw dbError;
      }

      if (user.length === 0) {
        logger.error({ parentId }, "User not found for push token removal");
        res.status(404).json({
          success: false,
          reason: "User not found",
        });
        return;
      }

      const currentTokens = user[0]!.pushTokens || [];
      const updatedTokens = currentTokens.filter((t) => t !== token);

      try {
        await db
          .update(users)
          .set({ pushTokens: updatedTokens })
          .where(eq(users.id, parentId));
        logger.info(
          {
            parentId,
            removedToken: currentTokens.includes(token),
            tokenCount: updatedTokens.length,
          },
          "Push token removal processed",
        );
      } catch (updateError) {
        logger.error(
          { error: updateError, parentId },
          "Database error removing push token",
        );
        throw updateError;
      }

      res.json({ success: true });
    } catch (e) {
      logger.error({ error: e, parentId }, "Failed to remove push token");
      res.status(500).json({
        success: false,
        reason: "Failed to remove push token",
      });
    }
  });

  // Get alerts for the parent
  router.get("/parent/alerts", authParent, async (req, res) => {
    const parentId = req.user!.id;

    try {
      let parentAlerts;
      try {
        parentAlerts = await db
          .select({
            id: alerts.id,
            deviceId: alerts.deviceId,
            deviceName: linkedDevices.nickname,
            category: alerts.category,
            title: alerts.title,
            message: alerts.message,
            summary: alerts.summary,
            confidence: alerts.confidence,
            packageName: alerts.packageName,
            timestamp: alerts.timestamp,
            read: alerts.read,
          })
          .from(alerts)
          .innerJoin(linkedDevices, eq(alerts.deviceId, linkedDevices.id))
          .where(eq(alerts.parentId, parentId))
          .orderBy(desc(alerts.timestamp));
      } catch (dbError) {
        logger.error(
          { error: dbError, parentId },
          "Database error fetching alerts",
        );
        throw dbError;
      }

      const formatTimeLabel = (timestamp: number): string => {
        const date = new Date(timestamp * 1000);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMins = Math.floor(diffMs / 1000 / 60);
        const diffHours = Math.floor(diffMins / 60);
        const diffDays = Math.floor(diffHours / 24);

        if (diffMins < 1) return "Just now";
        if (diffMins < 60) return `${diffMins}m ago`;
        if (diffHours < 24) return `${diffHours}h ago`;
        if (diffDays < 7) return `${diffDays}d ago`;
        return date.toLocaleDateString();
      };

      const formattedAlerts = parentAlerts.map((alert) => ({
        id: alert.id.toString(),
        title: alert.title,
        timeLabel: formatTimeLabel(alert.timestamp),
        whatHappened: `${alert.packageName || "An app"} on ${
          alert.deviceName
        } received: "${alert.message}"`,
        whyItMatters: alert.summary,
        suggestedAction:
          alert.category === "sexual_predator"
            ? "This requires immediate attention. Consider reviewing the device's activity and having a conversation with your child about online safety."
            : alert.category === "grooming"
              ? "Review this message carefully and discuss online safety with your child. Consider limiting contact with unknown individuals."
              : "Monitor this activity and discuss appropriate online behavior with your child.",
        severity: (alert.confidence >= 80 ? "needs_attention" : "gentle") as
          | "needs_attention"
          | "gentle",
      }));

      logger.debug(
        { parentId, alertCount: formattedAlerts.length },
        "Alerts retrieved successfully",
      );

      res.json({
        success: true,
        alerts: formattedAlerts,
      });
    } catch (e) {
      logger.error({ error: e, parentId }, "Failed to fetch alerts");
      res.status(500).json({
        success: false,
        reason: "Failed to fetch alerts",
      });
    }
  });

  return router;
}

export default createParentRouter;