All files / src/routes users.js

89.27% Statements 383/429
81.67% Branches 214/262
100% Functions 24/24
90.3% Lines 354/392

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                        6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x         74x 74x 12x 12x   62x             6x 28x   28x   28x 26x 24x 1x           23x 1x   22x 22x 2x   20x 20x 20x 20x         20x 20x 20x   20x   20x 20x     20x 3x 3x   2x       2x     1x         17x 17x 17x   17x     17x     17x                                           17x                 17x       17x     17x   17x 17x   3x 1x   2x 2x                         6x 11x 11x   11x 10x   9x 9x   9x 1x     8x 2x     6x     6x           6x     6x   6x 6x                     6x 30x 30x 30x   28x 28x 28x     28x 28x 28x 28x 28x 28x     28x 28x 28x 28x 28x     28x 28x 28x 28x 20x     28x                       6x                     6x             6x                       6x                     2x 18x     18x                 2x 20x   2x 12x     2x 4x     2x 4x     2x             6x 5x 5x   3x 3x   3x                                                       3x 3x 75x     3x 1x       2x 2x     2x       2x       2x   2x                           6x 19x 19x   18x 18x 17x 16x           16x 16x     16x         16x     16x 2x     14x   2x 2x       2x 4x       2x   2x         2x     12x           32x 12x 2x         10x     10x                   10x       10x   10x         10x                           6x 9x 9x   8x 8x 8x   8x 8x     8x         8x 8x     7x 1x       11x 6x 2x         4x     4x           4x 8x       4x   4x         4x                           6x 4x 4x   3x 3x 2x 1x         1x 1x   1x                             1x                           6x 5x 5x   4x 4x 4x 4x 1x     3x 3x 1x     2x   2x                 2x   2x                           6x 2x 2x 2x 2x 2x 1x     1x 1x 1x     1x     1x 1x   1x                             6x 3x 3x 3x 3x 2x   1x 1x 1x     1x     1x 1x   1x                             6x 3x 3x 3x 3x 2x   1x 1x 1x     1x     1x 1x   1x                             6x 5x 5x 5x 5x   4x 1x   3x   2x 2x 2x 2x   2x 1x 1x       1x     1x   1x 1x                   1x       1x     2x                         6x 6x 5x 5x 5x         6x 5x 5x                               6x 13x 13x   12x 12x     12x 11x 1x   10x     10x 1x       9x 1x     8x 1x   7x 7x 1x       6x 6x       6x 6x     6x           6x     6x 6x           6x     6x               6x 6x   1x 1x               6x 8x 8x   7x   7x 6x 1x   5x   5x 1x       4x 1x           3x 1x     2x             2x             2x 2x   1x 1x               6x 5x 5x   4x   4x 3x 1x   2x   2x 1x                 1x 1x   1x               1x 1x       6x  
/**
 * User routes — identity-based profile CRUD, sign-in, provider linking.
 *
 * POST   /api/users                          → Create new user (identity + uniqueId)
 * POST   /api/users/sign-in                  → Resolve identity, update firebaseUid
 * GET    /api/users/:uniqueId                → Get user profile
 * PATCH  /api/users/:uniqueId                → Update user profile fields
 * POST   /api/users/:uniqueId/link-provider  → Link additional provider
 * DELETE /api/users/:uniqueId/link-provider  → Soft-remove (unlink) provider
 * POST   /api/users/:uniqueId/appeal         → Submit suspension appeal
 * POST   /api/users/:uniqueId/lift-suspension→ Lift expired suspension
 * POST   /api/users/:uniqueId/follow         → Follow a user
 * POST   /api/users/:uniqueId/unfollow       → Unfollow a user
 * POST   /api/users/:uniqueId/remove-follower→ Remove a follower
 * POST   /api/users/:uniqueId/record-visit   → Record profile visit (stalker)
 * POST   /api/users/:uniqueId/delete         → Schedule account deletion (owner)
 * POST   /api/users/:uniqueId/cancel-delete  → Cancel scheduled deletion (owner)
 * GET    /api/users/:uniqueId/deletion-status → Check deletion status (owner)
 */
 
const router = require('express').Router();
const bcrypt = require('bcrypt');
const { db, auth, FieldValue } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const { getDoc } = require('../utils/firestore-helpers');
const log = require('../utils/log');
const { clearSuspensionCache, updateUniqueIdCache } = require('../middleware/auth');
const { sendEmail } = require('../utils/email');
const { buildDeletionScheduledEmail } = require('../utils/email-templates');
const { sendFcmToTokens } = require('../utils/fcm');
 
const VALID_PROVIDERS = ['google', 'apple', 'email'];
const MIN_UNIQUE_ID = 10000000;
const MAX_IDENTIFIERS_PER_PROVIDER = 5;
 
// ─── Helper: ownership check ────────────────────────────────────
 
function requireOwner(req, res) {
  const paramId = Number(req.params.uniqueId);
  if (req.auth.uniqueId !== paramId) {
    res.status(403).json({ error: 'Cannot modify another user' });
    return true; // blocked
  }
  return false;
}
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users — Create new user with identity map
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users', async (req, res) => {
  try {
    const { provider, identifier, displayName, email, profilePhotoUrl, dateOfBirth, language } =
      req.body || {};
 
    if (!provider) return res.status(400).json({ error: 'provider required' });
    if (!identifier) return res.status(400).json({ error: 'identifier required' });
    if (!VALID_PROVIDERS.includes(provider)) {
      return res
        .status(400)
        .json({ error: `Invalid provider. Must be one of: ${VALID_PROVIDERS.join(', ')}` });
    }
 
    // Server-side age validation — UK OSA + COPPA require minimum age 13
    if (!dateOfBirth) {
      return res.status(400).json({ error: 'Date of birth is required' });
    }
    const dob = new Date(dateOfBirth);
    if (Number.isNaN(dob.getTime())) {
      return res.status(400).json({ error: 'Invalid date of birth format' });
    }
    const ageDiff = Date.now() - dob.getTime();
    const ageDate = new Date(ageDiff);
    const age = Math.abs(ageDate.getUTCFullYear() - 1970);
    Iif (age < 13) {
      log.warn('users', 'Age validation rejected', { dateOfBirth });
      return res.status(403).json({ error: 'Must be at least 13 years old' });
    }
 
    const identityDocId = `${provider}:${identifier}`;
    const counterRef = db.doc('counters/uniqueId');
    const identityRef = db.doc(`identityMap/${identityDocId}`);
 
    const newUniqueId = await db.runTransaction(async (t) => {
      // All reads first (Firestore transaction requirement)
      const counterSnap = await t.get(counterRef);
      const identitySnap = await t.get(identityRef);
 
      // Check identity not already claimed
      if (identitySnap.exists) {
        const identityData = identitySnap.data();
        if (identityData.unlinked) {
          // Deleted accounts: allow clean re-registration, block suspended
          Iif (identityData.deletedAccount && identityData.deletionStanding === 'clean') {
            // Clean deletion — allow re-registration with new uniqueId
            // The old identity map entry will be replaced below
          } else {
            throw Object.assign(new Error('Identity deactivated'), { code: 'DEACTIVATED' });
          }
        } else {
          throw Object.assign(new Error('Identity already linked'), { code: 'ALREADY_LINKED' });
        }
      }
 
      // Atomic counter increment
      let current = counterSnap.exists ? counterSnap.data().value || 0 : 0;
      if (current < MIN_UNIQUE_ID) current = MIN_UNIQUE_ID - 1;
      const next = current + 1;
 
      const timestamp = now();
 
      // Write counter
      t.set(counterRef, { value: next }, { merge: true });
 
      // Write user doc
      t.set(db.doc(`users/${next}`), {
        uniqueId: next,
        firebaseUid: req.auth.uid,
        displayName: displayName || null,
        email: email || null,
        profilePhotoUrl: profilePhotoUrl || null,
        dateOfBirth: dateOfBirth || null,
        providers: [{ type: provider, identifier, active: true, linkedAt: timestamp }],
        userType: 'MEMBER',
        blockedUserIds: [],
        followingIds: [],
        followerIds: [],
        fcmTokens: [],
        aliases: {},
        language: language || 'en',
        stalkerCount: 0,
        newStalkerCount: 0,
        createdAt: timestamp,
        lastSeenAt: timestamp,
      });
 
      // Write identity map entry
      t.set(db.doc(`identityMap/${identityDocId}`), {
        uniqueId: next,
        provider,
        identifier,
        linkedAt: timestamp,
        unlinked: false,
        unlinkedAt: null,
      });
 
      return next;
    });
 
    // Set Firebase custom claims so Firestore security rules can use callerUniqueId()
    await auth.setCustomUserClaims(req.auth.uid, { uniqueId: newUniqueId });
 
    // Update uid → uniqueId cache so subsequent requests resolve instantly
    updateUniqueIdCache(req.auth.uid, newUniqueId);
 
    log.info('users', 'New user created', { uniqueId: newUniqueId, provider });
    res.json({ success: true, created: true, uniqueId: newUniqueId });
  } catch (err) {
    if (err.code === 'ALREADY_LINKED') {
      return res.status(409).json({ error: 'Identity already linked to an account' });
    }
    Eif (err.code === 'DEACTIVATED') {
      return res
        .status(409)
        .json({ error: 'This identity has been deactivated. Contact support for assistance.' });
    }
    log.error('users', 'POST /users failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/sign-in — Identity resolution + firebaseUid update
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/sign-in', async (req, res) => {
  try {
    const { provider, identifier } = req.body || {};
 
    if (!provider) return res.status(400).json({ error: 'provider required' });
    if (!identifier) return res.status(400).json({ error: 'identifier required' });
 
    const identityDocId = `${provider}:${identifier}`;
    const identity = await getDoc(`identityMap/${identityDocId}`);
 
    if (!identity) {
      return res.json({ found: false });
    }
 
    if (identity.unlinked) {
      return res.json({ found: false, deactivated: true });
    }
 
    const uniqueId = identity.uniqueId;
 
    // Update firebaseUid to current project's UID + refresh lastSeenAt
    await db.doc(`users/${uniqueId}`).update({
      firebaseUid: req.auth.uid,
      lastSeenAt: now(),
    });
 
    // Set Firebase custom claims so Firestore security rules can use callerUniqueId()
    await auth.setCustomUserClaims(req.auth.uid, { uniqueId });
 
    // Update caches
    updateUniqueIdCache(req.auth.uid, uniqueId);
 
    log.info('users', 'User signed in via identity', { uniqueId, provider });
    res.json({ found: true, uniqueId });
  } catch (err) {
    log.error('users', 'POST /users/sign-in failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// GET /api/users/:uniqueId — Get user profile
// ═══════════════════════════════════════════════════════════════════
 
router.get('/users/:uniqueId', async (req, res) => {
  try {
    const user = await getDoc(`users/${req.params.uniqueId}`);
    if (!user) return res.status(404).json({ error: 'User not found' });
 
    user.blockedUserIds = user.blockedUserIds || [];
    user.followingIds = user.followingIds || [];
    user.followerIds = user.followerIds || [];
 
    // Strip admin-only fields
    delete user.gcsScore;
    delete user.gcsLastDeductionAt;
    delete user.gcsDisplayScore;
    delete user.warningCount;
    delete user.warningIssuedAt;
    delete user.hasNewWarning;
 
    // Strip sensitive / PII fields
    delete user.pinHash;
    delete user.fcmTokens;
    delete user.firebaseUid;
    delete user.email;
    delete user.dateOfBirth;
 
    // Strip deletion fields (only visible to owner via /deletion-status)
    delete user.deletionScheduledAt;
    delete user.deletionReason;
    delete user.deletionExecuteAt;
    if (Array.isArray(user.providers)) {
      user.providers = user.providers.map(({ identifier: _identifier, ...rest }) => rest);
    }
 
    res.json(user);
  } catch (err) {
    log.error('users', 'GET /users/:uniqueId failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Profile update validation ─────────────────────────────────
 
const PROFILE_STRING_FIELDS = [
  'displayName',
  'description',
  'nationality',
  'profilePhotoUrl',
  'coverPhotoUrl',
  'pmPrivacy',
  'currentRoomId',
  'lastRoomName',
  'language',
];
const PROFILE_MAX_LENGTHS = {
  displayName: 20,
  description: 200,
  nationality: 3,
  language: 10,
  lastRoomName: 50,
};
const PROFILE_BOOL_FIELDS = [
  'pmNotificationsEnabled',
  'pmSoundEnabled',
  'pmShowTimestamps',
  'pmShowDateSeparators',
  'pmNotificationPreview',
  'hideFollowing',
  'hideOnlineStatus',
  'hideAge',
  'selfDestructAlertEnabled',
  'dndEnabled',
];
const PROFILE_INT_FIELDS = [
  'dndStartHour',
  'dndStartMinute',
  'dndEndHour',
  'dndEndMinute',
  'minGiftAnimationValue',
  'acceptedLegalVersion',
];
 
/** Validate profile update field types and constraints. Returns error string or null. */
function validateProfileUpdates(updates) {
  for (const key of PROFILE_STRING_FIELDS) {
    Iif (key in updates && updates[key] !== null && typeof updates[key] !== 'string') {
      return `${key} must be a string`;
    }
    Iif (
      key in updates &&
      typeof updates[key] === 'string' &&
      PROFILE_MAX_LENGTHS[key] &&
      updates[key].length > PROFILE_MAX_LENGTHS[key]
    ) {
      return `${key} exceeds max length of ${PROFILE_MAX_LENGTHS[key]}`;
    }
  }
  for (const key of PROFILE_BOOL_FIELDS) {
    Iif (key in updates && typeof updates[key] !== 'boolean') return `${key} must be a boolean`;
  }
  for (const key of PROFILE_INT_FIELDS) {
    Iif (key in updates && (typeof updates[key] !== 'number' || !Number.isInteger(updates[key])))
      return `${key} must be an integer`;
  }
  for (const key of ['dndStartHour', 'dndEndHour']) {
    Iif (key in updates && (updates[key] < 0 || updates[key] > 23))
      return `${key} must be between 0 and 23`;
  }
  for (const key of ['dndStartMinute', 'dndEndMinute']) {
    Iif (key in updates && (updates[key] < 0 || updates[key] > 59))
      return `${key} must be between 0 and 59`;
  }
  return null;
}
 
// ═══════════════════════════════════════════════════════════════════
// PATCH /api/users/:uniqueId — Update user profile
// ═══════════════════════════════════════════════════════════════════
 
router.patch('/users/:uniqueId', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const body = req.body;
    Iif (!body) return res.status(400).json({ error: 'Invalid JSON body' });
 
    const allowedFields = [
      'displayName',
      'description',
      'nationality',
      'profilePhotoUrl',
      'coverPhotoUrl',
      'pmPrivacy',
      'pmNotificationsEnabled',
      'pmSoundEnabled',
      'pmShowTimestamps',
      'pmShowDateSeparators',
      'pmNotificationPreview',
      'hideFollowing',
      'hideOnlineStatus',
      'hideAge',
      'selfDestructAlertEnabled',
      'minGiftAnimationValue',
      'dndEnabled',
      'dndStartHour',
      'dndStartMinute',
      'dndEndHour',
      'dndEndMinute',
      'acceptedLegalVersion',
      'currentRoomId',
      'lastRoomName',
      'language',
    ];
 
    const updates = {};
    for (const key of allowedFields) {
      if (key in body) updates[key] = body[key];
    }
 
    if (Object.keys(updates).length === 0) {
      return res.status(400).json({ error: 'No valid fields to update' });
    }
 
    // Validate field value types and lengths
    const validationError = validateProfileUpdates(updates);
    Iif (validationError) return res.status(400).json({ error: validationError });
 
    // GDPR consent audit trail — store acceptance timestamp
    Iif (updates.acceptedLegalVersion !== undefined) {
      updates.legalAcceptedAt = Date.now();
    }
 
    log.info('users', 'Updating profile', {
      uniqueId: req.params.uniqueId,
      fields: Object.keys(updates),
    });
    await db.doc(`users/${req.params.uniqueId}`).update(updates);
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'PATCH /users/:uniqueId failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/link-provider — Link additional provider
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/link-provider', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const { provider, identifier } = req.body || {};
    if (!provider) return res.status(400).json({ error: 'provider required' });
    if (!identifier) return res.status(400).json({ error: 'identifier required' });
    Iif (!VALID_PROVIDERS.includes(provider)) {
      return res
        .status(400)
        .json({ error: `Invalid provider. Must be one of: ${VALID_PROVIDERS.join(', ')}` });
    }
 
    const uniqueId = Number(req.params.uniqueId);
    const identityDocId = `${provider}:${identifier}`;
 
    // Load user doc + identity map entry in parallel
    const [user, existingIdentity] = await Promise.all([
      getDoc(`users/${uniqueId}`),
      getDoc(`identityMap/${identityDocId}`),
    ]);
 
    Iif (!user) return res.status(404).json({ error: 'User not found' });
 
    // Check if identity is already claimed
    if (existingIdentity && existingIdentity.uniqueId !== uniqueId) {
      return res.status(409).json({ error: 'This identity is already linked to another account' });
    }
 
    if (existingIdentity && existingIdentity.unlinked) {
      // Re-linking own deactivated identity
      const timestamp = now();
      await db
        .doc(`identityMap/${identityDocId}`)
        .update({ unlinked: false, unlinkedAt: null, linkedAt: timestamp });
 
      const providers = (user.providers || []).map((p) =>
        p.type === provider && p.identifier === identifier
          ? { ...p, active: true, linkedAt: timestamp, unlinkedAt: undefined }
          : p,
      );
      await db.doc(`users/${uniqueId}`).update({ providers });
 
      log.info('users', 'Provider re-linked', {
        uniqueId,
        provider,
        identifier: identifier.includes('@') ? `***@${identifier.split('@')[1]}` : '***',
      });
      return res.json({ success: true, relinked: true });
    }
 
    Iif (existingIdentity) {
      // Already active — no-op
      return res.json({ success: true, alreadyLinked: true });
    }
 
    // Check provider count limit
    const existingOfType = (user.providers || []).filter((p) => p.type === provider && p.active);
    if (existingOfType.length >= MAX_IDENTIFIERS_PER_PROVIDER) {
      return res
        .status(409)
        .json({ error: 'Unable to link this account. Please contact support for assistance.' });
    }
 
    const timestamp = now();
 
    // Create identity map entry
    await db.doc(`identityMap/${identityDocId}`).set({
      uniqueId,
      provider,
      identifier,
      linkedAt: timestamp,
      unlinked: false,
      unlinkedAt: null,
    });
 
    // Update providers array
    const providers = [
      ...(user.providers || []),
      { type: provider, identifier, active: true, linkedAt: timestamp },
    ];
    await db.doc(`users/${uniqueId}`).update({ providers });
 
    log.info('users', 'Provider linked', {
      uniqueId,
      provider,
      identifier: identifier.includes('@') ? `***@${identifier.split('@')[1]}` : '***',
    });
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Link provider failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// DELETE /api/users/:uniqueId/link-provider — Soft-remove provider
// ═══════════════════════════════════════════════════════════════════
 
router.delete('/users/:uniqueId/link-provider', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const { provider, identifier } = req.body || {};
    Iif (!provider) return res.status(400).json({ error: 'provider required' });
    Iif (!identifier) return res.status(400).json({ error: 'identifier required' });
 
    const uniqueId = Number(req.params.uniqueId);
    const identityDocId = `${provider}:${identifier}`;
 
    // Load user doc + identity map entry
    const [user, identity] = await Promise.all([
      getDoc(`users/${uniqueId}`),
      getDoc(`identityMap/${identityDocId}`),
    ]);
 
    Iif (!user) return res.status(404).json({ error: 'User not found' });
    if (!identity) return res.status(404).json({ error: 'Identity not found' });
 
    // Verify identity belongs to this user
    if (identity.uniqueId !== uniqueId) {
      return res.status(403).json({ error: 'Identity does not belong to this user' });
    }
 
    // Check at least 2 active providers remain
    const activeProviders = (user.providers || []).filter((p) => p.active);
    if (activeProviders.length < 2) {
      return res.status(400).json({
        error: 'Cannot unlink your only active provider. At least one provider must remain linked.',
      });
    }
 
    const timestamp = now();
 
    // Soft-remove identity map entry
    await db.doc(`identityMap/${identityDocId}`).update({
      unlinked: true,
      unlinkedAt: timestamp,
    });
 
    // Update providers array — set active=false + unlinkedAt
    const providers = (user.providers || []).map((p) =>
      p.type === provider && p.identifier === identifier
        ? { ...p, active: false, unlinkedAt: timestamp }
        : p,
    );
    await db.doc(`users/${uniqueId}`).update({ providers });
 
    log.info('users', 'Provider unlinked', {
      uniqueId,
      provider,
      identifier: identifier.includes('@') ? `***@${identifier.split('@')[1]}` : '***',
    });
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Unlink provider failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/appeal — Suspension appeal
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/appeal', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const body = req.body;
    if (!body?.appealText) return res.status(400).json({ error: 'appealText required' });
    if (typeof body.appealText !== 'string' || body.appealText.length > 500) {
      return res
        .status(400)
        .json({ error: 'appealText must be a string of at most 500 characters' });
    }
 
    const uniqueId = req.params.uniqueId;
    log.info('users', 'Suspension appeal submitted', { uniqueId });
 
    await Promise.all([
      db.doc(`suspensionAppeals/${generateId()}`).set(
        {
          uniqueId,
          appealText: body.appealText,
          status: 'pending',
          createdAt: now(),
        },
        { merge: true },
      ),
      db.doc(`users/${uniqueId}`).update({
        suspensionAppealStatus: 'pending',
      }),
    ]);
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Suspension appeal failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/lift-suspension — Lift expired suspension
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/lift-suspension', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
    const user = await getDoc(`users/${uniqueId}`);
    const isSuspended = user?.isSuspended ?? user?.is_suspended ?? false;
    if (!user || !isSuspended) {
      return res.status(400).json({ error: 'User is not suspended' });
    }
 
    const suspensionEndDate = user.suspensionEndDate ?? user.suspension_end_date ?? null;
    if (suspensionEndDate && suspensionEndDate > now()) {
      return res.status(400).json({ error: 'Suspension has not expired yet' });
    }
 
    log.info('users', 'Lifting expired suspension', { uniqueId });
 
    await db.doc(`users/${uniqueId}`).update({
      isSuspended: false,
      suspensionReason: null,
      suspensionEndDate: null,
      suspensionCanAppeal: true,
      suspensionAppealStatus: null,
      suspendedBy: null,
    });
 
    clearSuspensionCache(Number(uniqueId));
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Lift suspension failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/follow — Follow a user
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/follow', async (req, res) => {
  try {
    const body = req.body;
    const targetId = body?.targetUserId;
    Iif (!targetId) return res.status(400).json({ error: 'targetUserId required' });
    if (requireOwner(req, res)) return;
    Iif (String(req.params.uniqueId) === String(targetId))
      return res.status(400).json({ error: 'Cannot follow yourself' });
 
    const uniqueId = req.params.uniqueId;
    const batch = db.batch();
    batch.update(db.doc(`users/${uniqueId}`), {
      followingIds: FieldValue.arrayUnion(Number(targetId)),
    });
    batch.update(db.doc(`users/${targetId}`), {
      followerIds: FieldValue.arrayUnion(Number(uniqueId)),
    });
    await batch.commit();
    log.info('users', 'User followed', { uniqueId, targetUserId: targetId });
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Follow failed', {
      uniqueId: req.params.uniqueId,
      targetUserId: req.body?.targetUserId,
      error: err.message,
    });
    res.status(500).json({ error: 'Failed to follow user' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/unfollow — Unfollow a user
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/unfollow', async (req, res) => {
  try {
    const body = req.body;
    const targetId = body?.targetUserId;
    if (!targetId) return res.status(400).json({ error: 'targetUserId required' });
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
    const batch = db.batch();
    batch.update(db.doc(`users/${uniqueId}`), {
      followingIds: FieldValue.arrayRemove(Number(targetId)),
    });
    batch.update(db.doc(`users/${targetId}`), {
      followerIds: FieldValue.arrayRemove(Number(uniqueId)),
    });
    await batch.commit();
    log.info('users', 'User unfollowed', { uniqueId, targetUserId: targetId });
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Unfollow failed', {
      uniqueId: req.params.uniqueId,
      targetUserId: req.body?.targetUserId,
      error: err.message,
    });
    res.status(500).json({ error: 'Failed to unfollow user' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/remove-follower — Remove a follower
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/remove-follower', async (req, res) => {
  try {
    const body = req.body;
    const followerId = body?.followerUserId;
    if (!followerId) return res.status(400).json({ error: 'followerUserId required' });
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
    const batch = db.batch();
    batch.update(db.doc(`users/${uniqueId}`), {
      followerIds: FieldValue.arrayRemove(Number(followerId)),
    });
    batch.update(db.doc(`users/${followerId}`), {
      followingIds: FieldValue.arrayRemove(Number(uniqueId)),
    });
    await batch.commit();
    log.info('users', 'Follower removed', { uniqueId, followerUserId: followerId });
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Remove follower failed', {
      uniqueId: req.params.uniqueId,
      followerUserId: req.body?.followerUserId,
      error: err.message,
    });
    res.status(500).json({ error: 'Failed to remove follower' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/record-visit — Record profile visit
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/record-visit', async (req, res) => {
  try {
    const body = req.body;
    const visitorId = body?.visitorId;
    if (!visitorId) return res.status(400).json({ error: 'visitorId required' });
    // visitorId must match caller's uniqueId (string comparison since param is string)
    if (String(req.auth.uniqueId) !== String(visitorId)) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    if (req.params.uniqueId === visitorId) return res.json({ success: true }); // don't stalk yourself
 
    const profileUniqueId = req.params.uniqueId;
    const stalkerPath = `users/${profileUniqueId}/stalkers/${visitorId}`;
    const existing = await getDoc(stalkerPath);
    const timestamp = now();
 
    if (existing) {
      const batch = db.batch();
      batch.update(db.doc(stalkerPath), {
        lastVisitedAt: timestamp,
        visitCount: (existing.visitCount || 1) + 1,
      });
      batch.update(db.doc(`users/${profileUniqueId}`), {
        newStalkerCount: FieldValue.increment(1),
      });
      await batch.commit();
    } else {
      const batch = db.batch();
      batch.set(
        db.doc(stalkerPath),
        {
          visitorId,
          lastVisitedAt: timestamp,
          firstVisitedAt: timestamp,
          visitCount: 1,
        },
        { merge: true },
      );
      batch.update(db.doc(`users/${profileUniqueId}`), {
        stalkerCount: FieldValue.increment(1),
        newStalkerCount: FieldValue.increment(1),
      });
      await batch.commit();
    }
 
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Record visit failed', {
      profileUniqueId: req.params.uniqueId,
      visitorId: req.body?.visitorId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
/** Send email and push notification for scheduled account deletion. */
async function sendDeletionNotifications(user, executeAt) {
  const deleteDate = new Date(executeAt).toISOString().split('T')[0];
  if (user.email) {
    try {
      const template = buildDeletionScheduledEmail(deleteDate);
      await sendEmail(user.email, template.subject, template.html);
    } catch (emailErr) {
      log.error('users', 'Failed to send deletion email', { error: emailErr.message });
    }
  }
  if (user.fcmTokens && user.fcmTokens.length > 0) {
    try {
      await sendFcmToTokens(user.fcmTokens, {
        notification: {
          title: 'Account Deletion Scheduled',
          body: `Your account will be deleted on ${deleteDate}. Sign in to cancel.`,
        },
      });
    } catch (fcmErr) {
      log.error('users', 'Failed to send deletion push', { error: fcmErr.message });
    }
  }
}
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/delete — Schedule account deletion
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/delete', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
    const { pin } = req.body || {};
 
    // Fetch user
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) {
      return res.status(404).json({ error: 'User not found' });
    }
    const user = userSnap.data();
 
    // Check if already scheduled
    if (user.deletionScheduledAt) {
      return res.status(409).json({ error: 'Deletion already scheduled' });
    }
 
    // Verify identity: PIN required
    if (!pin) {
      return res.status(400).json({ error: 'PIN verification required' });
    }
 
    if (!user.pinHash) {
      return res.status(400).json({ error: 'No PIN set for this account' });
    }
    const isValid = await bcrypt.compare(pin, user.pinHash);
    if (!isValid) {
      return res.status(401).json({ error: 'Wrong PIN' });
    }
 
    // Get grace period from config
    const configSnap = await db.doc('config/app').get();
    const graceDays = configSnap.exists
      ? configSnap.data().accountDeletionGracePeriodDays || 30
      : 30;
 
    const timestamp = now();
    const executeAt = timestamp + graceDays * 86400000;
 
    // Set deletion fields + clear room
    const updates = {
      deletionScheduledAt: timestamp,
      deletionReason: 'self',
      deletionExecuteAt: executeAt,
      currentRoomId: null,
    };
    await db.doc(`users/${uniqueId}`).update(updates);
 
    // Revoke refresh tokens (sign out all devices)
    try {
      await auth.revokeRefreshTokens(user.firebaseUid);
    } catch (revokeErr) {
      log.error('users', 'Failed to revoke refresh tokens', { error: revokeErr.message });
    }
 
    // Send deletion notifications (best-effort)
    await sendDeletionNotifications(user, executeAt);
 
    // Audit log
    await db.doc(`adminAuditLog/${generateId()}`).set({
      action: 'ACCOUNT_DELETION_SCHEDULED',
      targetUserId: uniqueId,
      triggeredBy: 'self',
      reason: 'self',
      createdAt: timestamp,
    });
 
    log.info('users', 'Account deletion scheduled', { uniqueId, executeAt });
    res.json({ success: true, deleteAt: executeAt });
  } catch (err) {
    log.error('users', 'Failed to schedule account deletion', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// POST /api/users/:uniqueId/cancel-delete — Cancel scheduled deletion
// ═══════════════════════════════════════════════════════════════════
 
router.post('/users/:uniqueId/cancel-delete', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
 
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) {
      return res.status(404).json({ error: 'User not found' });
    }
    const user = userSnap.data();
 
    if (!user.deletionScheduledAt) {
      return res.status(404).json({ error: 'No deletion scheduled' });
    }
 
    // Admin-initiated deletions cannot be cancelled by the user
    if (user.deletionReason === 'admin') {
      return res
        .status(403)
        .json({ error: 'Admin-initiated deletion cannot be cancelled by the user' });
    }
 
    // Check if deletion already executed
    if (user.deletionExecuteAt && user.deletionExecuteAt <= now()) {
      return res.status(410).json({ error: 'Deletion has already been executed' });
    }
 
    await db.doc(`users/${uniqueId}`).update({
      deletionScheduledAt: null,
      deletionReason: null,
      deletionExecuteAt: null,
    });
 
    // Audit log
    await db.doc(`adminAuditLog/${generateId()}`).set({
      action: 'ACCOUNT_DELETION_CANCELLED',
      targetUserId: uniqueId,
      triggeredBy: 'self',
      createdAt: now(),
    });
 
    log.info('users', 'Account deletion cancelled', { uniqueId });
    res.json({ success: true });
  } catch (err) {
    log.error('users', 'Failed to cancel account deletion', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ═══════════════════════════════════════════════════════════════════
// GET /api/users/:uniqueId/deletion-status — Check deletion status
// ═══════════════════════════════════════════════════════════════════
 
router.get('/users/:uniqueId/deletion-status', async (req, res) => {
  try {
    if (requireOwner(req, res)) return;
 
    const uniqueId = req.params.uniqueId;
 
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) {
      return res.status(404).json({ error: 'User not found' });
    }
    const user = userSnap.data();
 
    if (!user.deletionScheduledAt) {
      return res.json({
        scheduled: false,
        scheduledAt: null,
        executeAt: null,
        reason: null,
        daysRemaining: null,
      });
    }
 
    const msRemaining = user.deletionExecuteAt - now();
    const daysRemaining = Math.max(0, Math.ceil(msRemaining / 86400000));
 
    res.json({
      scheduled: true,
      scheduledAt: user.deletionScheduledAt,
      executeAt: user.deletionExecuteAt,
      reason: user.deletionReason,
      daysRemaining,
    });
  } catch (err) {
    log.error('users', 'Failed to get deletion status', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;