All files / src/routes admin-cleanup.js

30.85% Statements 191/619
27.81% Branches 42/151
46.03% Functions 29/63
29.68% Lines 160/539

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 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108                                                              1x 1x 1x 1x 1x 1x   1x                                                                                                                                                     1x 1x 1x                                                                                       1x 1x 1x                                           1x 1x 1x                                                                       1x 1x 1x                                                                             1x 1x 1x                                                               1x 1x 1x                                                               1x 3x 3x   2x   2x 2x   2x 1x 1x 2x   1x     2x               1x 1x 1x                                             1x 1x 1x                                                                                               1x 1x 1x                                                       1x 1x 1x                                                               1x 1x 1x                                             1x 1x 1x                                                                                                     1x 1x 1x                                                                 1x 1x 1x                                                                                                 1x 1x 1x                                                               1x 1x 1x                                                     1x 1x 1x                                                     1x 4x 4x   3x       3x 5x   5x 2x   2x 1x     1x 1x 1x 2x   1x     1x       2x     1x 1x         1x 3x 3x   2x   2x 2x   2x 1x     1x 1x 1x 3x   1x     1x               1x 6x 6x   4x 4x   4x 4x       4x         4x   4x 2x     2x 2x 3x   2x   2x                             1x 4x 4x   3x                 3x 3x 3x   3x 15x 14x 14x 14x 14x     14x 14x 14x 14x     2x   1x 1x                                                                                                                                                                                         1x 1x 1x                                                                     1x 1x 1x                                                                                                 1x 4x 4x 2x 1x   1x       1x         1x 4x 4x 2x 1x   1x       1x       1x  
/**
 * Admin cleanup routes — data reset, storage audit, orphan cleanup.
 *
 * All endpoints require admin. They operate on Firestore collections and R2 directly.
 *
 * POST /api/cleanup/system-conversations       → Delete duplicate system conversations
 * POST /api/cleanup/all-system-conversations    → Delete ALL system conversations
 * POST /api/cleanup/all-reports                 → Delete all reports + locks
 * POST /api/cleanup/all-warnings               → Reset warnings on all users
 * POST /api/cleanup/all-backpacks              → Clear all backpack items
 * POST /api/cleanup/all-giftwalls              → Clear all gift walls
 * POST /api/cleanup/all-coins                  → Reset all coin balances
 * POST /api/cleanup/all-beans                  → Reset all bean balances
 * POST /api/cleanup/all-spin-history           → Delete gacha transactions + reset pity
 * POST /api/cleanup/all-transactions          → Delete ALL transaction records
 * POST /api/cleanup/all-supershy               → Clear Super Shy status
 * POST /api/cleanup/all-appeals                → Delete all suspension appeals
 * POST /api/cleanup/backfill-user-type          → Set userType=MEMBER for users missing it
 * POST /api/cleanup/all-private-messages       → Delete all 1-on-1 PMs + R2 media
 * POST /api/cleanup/all-group-chats            → Delete all group chats + R2 media
 * POST /api/cleanup/all-rooms                  → Delete all closed rooms + subcollections
 * POST /api/cleanup/all-broadcasts             → Delete all broadcast records
 * POST /api/cleanup/all-audit-logs             → Delete all admin audit logs
 * POST /api/cleanup/destroyed-users            → Delete corrupted user profiles
 * POST /api/cleanup/all-device-bindings        → Delete all device bindings
 * POST /api/cleanup/device-binding/:uniqueId   → Delete device binding for a user
 * GET  /api/storage/audit                      → R2 folder audit
 * POST /api/cleanup/orphaned-storage           → Smart R2 cleanup
 * POST /api/cleanup/all-stalkers              → Delete all stalker records + reset counts
 */
 
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { requireAdmin } = require('../middleware/auth');
const r2 = require('../utils/r2');
const { queryDocs } = require('../utils/firestore-helpers');
const log = require('../utils/log');
 
const listObjectsWithMeta = r2.listObjectsWithMetadata;
 
/**
 * Delete a conversation and all its associated subcollection data from Firestore.
 */
async function deleteConversation(convId) {
  const [messages, userSettings, mutes] = await Promise.all([
    queryDocs(db.collection(`conversations/${convId}/messages`)),
    queryDocs(db.collection(`conversations/${convId}/userSettings`)),
    queryDocs(db.collection(`conversations/${convId}/mutes`)),
  ]);
 
  const allDocs = [
    ...messages.map((m) => `conversations/${convId}/messages/${m.id}`),
    ...userSettings.map((s) => `conversations/${convId}/userSettings/${s.id}`),
    ...mutes.map((m) => `conversations/${convId}/mutes/${m.id}`),
    `conversations/${convId}`,
  ];
 
  for (let i = 0; i < allDocs.length; i += 500) {
    const batch = db.batch();
    for (const path of allDocs.slice(i, i + 500)) {
      batch.delete(db.doc(path));
    }
    await batch.commit();
  }
}
 
/**
 * Delete a room and all its associated subcollection data from Firestore.
 */
async function deleteRoom(roomId) {
  const [messages, seatRequests] = await Promise.all([
    queryDocs(db.collection(`rooms/${roomId}/messages`)),
    queryDocs(db.collection(`rooms/${roomId}/seatRequests`)),
  ]);
 
  const allDocs = [
    ...messages.map((m) => `rooms/${roomId}/messages/${m.id}`),
    ...seatRequests.map((s) => `rooms/${roomId}/seatRequests/${s.id}`),
    `rooms/${roomId}`,
  ];
 
  for (let i = 0; i < allDocs.length; i += 500) {
    const batch = db.batch();
    for (const path of allDocs.slice(i, i + 500)) {
      batch.delete(db.doc(path));
    }
    await batch.commit();
  }
 
  // Clean up RTDB presence and events for this room
  try {
    const { rtdb } = require('../utils/firebase');
    await rtdb.ref(`rooms/${roomId}`).remove();
  } catch (err) {
    log.error('admin-cleanup', 'Failed to clear RTDB for room', { roomId, error: err.message });
  }
}
 
/**
 * Delete all R2 objects under a prefix.
 */
async function deleteR2Prefix(prefix) {
  const keys = await r2.listObjects(prefix);
  if (keys.length > 0) {
    await r2.deleteObjects(keys);
  }
}
 
// ══════════════════════════════════════════════════════════════
// CLEANUP ROUTES
// ══════════════════════════════════════════════════════════════
 
// ── Delete duplicate system conversations ──
router.post('/cleanup/system-conversations', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting duplicate system conversations', {
      adminId: req.auth.uniqueId,
    });
 
    const snap = await db
      .collection('conversations')
      .where('participantIds', 'array-contains', 'SHYTALK_SYSTEM')
      .get();
    const systemConvs = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    let deleted = 0;
    const seen = new Map(); // recipientUid → first conversation id
 
    for (const conv of systemConvs) {
      const participantIds = conv.participantIds || [];
      const otherUid = participantIds.find((id) => id !== 'SHYTALK_SYSTEM');
      if (!otherUid) continue;
 
      const expectedId = [otherUid, 'SHYTALK_SYSTEM'].sort((a, b) => a.localeCompare(b)).join('_');
 
      if (conv.id === expectedId) {
        seen.set(otherUid, conv.id);
        continue;
      }
 
      // This is a duplicate — delete it
      if (seen.has(otherUid)) {
        await deleteConversation(conv.id);
        deleted++;
      } else {
        seen.set(otherUid, conv.id);
      }
    }
 
    res.json({ success: true, deleted });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup system conversations failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete ALL system conversations ──
router.post('/cleanup/all-system-conversations', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all system conversations', { adminId: req.auth.uniqueId });
 
    const snap = await db
      .collection('conversations')
      .where('participantIds', 'array-contains', 'SHYTALK_SYSTEM')
      .get();
    const systemConvs = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    for (const conv of systemConvs) {
      await deleteConversation(conv.id);
    }
 
    res.json({ success: true, deleted: systemConvs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all system conversations failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete all reports ──
router.post('/cleanup/all-reports', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all reports', { adminId: req.auth.uniqueId });
 
    // Delete R2 evidence files first
    await deleteR2Prefix('evidence/');
 
    // Delete all docs from reports, reportsArchive, reportLocks collections
    const [reports, reportsArchive, reportLocks] = await Promise.all([
      queryDocs(db.collection('reports')),
      queryDocs(db.collection('reportsArchive')),
      queryDocs(db.collection('reportLocks')),
    ]);
 
    const allDocs = [
      ...reports.map((d) => `reports/${d.id}`),
      ...reportsArchive.map((d) => `reportsArchive/${d.id}`),
      ...reportLocks.map((d) => `reportLocks/${d.id}`),
    ];
 
    for (let i = 0; i < allDocs.length; i += 500) {
      const batch = db.batch();
      for (const path of allDocs.slice(i, i + 500)) {
        batch.delete(db.doc(path));
      }
      await batch.commit();
    }
 
    res.json({ success: true });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all reports failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Reset all warnings ──
router.post('/cleanup/all-warnings', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Resetting all warnings', { adminId: req.auth.uniqueId });
 
    const [usersSnap, activeSnap] = await Promise.all([
      db.collection('users').where('warningCount', '>', 0).get(),
      db.collection('users').where('hasActiveWarning', '==', true).get(),
    ]);
 
    const allIds = new Set([
      ...usersSnap.docs.map((d) => d.id),
      ...activeSnap.docs.map((d) => d.id),
    ]);
 
    const uids = Array.from(allIds);
    for (let i = 0; i < uids.length; i += 500) {
      const batch = db.batch();
      for (const uid of uids.slice(i, i + 500)) {
        batch.update(db.doc(`users/${uid}`), {
          gcsScore: 100,
          gcsLastDeductionAt: null,
          warningCount: 0,
          hasActiveWarning: false,
          hasNewWarning: false,
          warningReason: null,
          warningIssuedAt: null,
        });
      }
      await batch.commit();
    }
 
    res.json({ success: true, affected: allIds.size });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all warnings failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Clear all backpacks ──
router.post('/cleanup/all-backpacks', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Clearing all backpacks', { adminId: req.auth.uniqueId });
 
    const usersSnap = await db.collection('users').orderBy('uid').get();
    const users = usersSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    let deleted = 0;
    for (const user of users) {
      const uid = user.uid ?? user.id;
      const itemsSnap = await db.collection(`users/${uid}/backpack`).get();
      if (itemsSnap.empty) continue;
 
      const items = itemsSnap.docs;
      for (let i = 0; i < items.length; i += 500) {
        const batch = db.batch();
        for (const item of items.slice(i, i + 500)) {
          batch.delete(item.ref);
        }
        await batch.commit();
      }
      deleted += items.length;
    }
 
    res.json({ success: true, deleted });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all backpacks failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Clear all gift walls ──
router.post('/cleanup/all-giftwalls', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Clearing all gift walls', { adminId: req.auth.uniqueId });
 
    const usersSnap = await db.collection('users').orderBy('uid').get();
    const users = usersSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    let deleted = 0;
    for (const user of users) {
      const uid = user.uid ?? user.id;
      const giftsSnap = await db.collection(`users/${uid}/giftWall`).get();
      if (giftsSnap.empty) continue;
 
      const gifts = giftsSnap.docs;
      for (let i = 0; i < gifts.length; i += 500) {
        const batch = db.batch();
        for (const gift of gifts.slice(i, i + 500)) {
          batch.delete(gift.ref);
        }
        await batch.commit();
      }
      deleted += gifts.length;
    }
 
    res.json({ success: true, deleted });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all gift walls failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Reset all coins ──
router.post('/cleanup/all-coins', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Resetting all coin balances', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('users').where('shyCoins', '>', 0).get();
    const docs = snap.docs;
 
    for (let i = 0; i < docs.length; i += 500) {
      const batch = db.batch();
      for (const doc of docs.slice(i, i + 500)) {
        batch.update(doc.ref, { shyCoins: 0 });
      }
      await batch.commit();
    }
 
    res.json({ success: true, affected: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all coins failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Reset all beans ──
router.post('/cleanup/all-beans', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Resetting all bean balances', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('users').where('shyBeans', '>', 0).get();
    const docs = snap.docs;
 
    for (let i = 0; i < docs.length; i += 500) {
      const batch = db.batch();
      for (const doc of docs.slice(i, i + 500)) {
        batch.update(doc.ref, { shyBeans: 0 });
      }
      await batch.commit();
    }
 
    res.json({ success: true, affected: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all beans failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete gacha spin history + reset pity ──
router.post('/cleanup/all-spin-history', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all spin history', { adminId: req.auth.uniqueId });
 
    // Clear pity counters on all users who have one
    const pitySnap = await db.collection('users').where('pityCounter', '>', 0).get();
    const pityDocs = pitySnap.docs;
 
    for (let i = 0; i < pityDocs.length; i += 500) {
      const batch = db.batch();
      for (const doc of pityDocs.slice(i, i + 500)) {
        batch.update(doc.ref, { pityCounter: 0 });
      }
      await batch.commit();
    }
 
    // Delete GACHA_PULL transactions from every user's transactions subcollection
    const usersSnap = await db.collection('users').orderBy('uid').get();
    const users = usersSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    let txDeleted = 0;
    for (const user of users) {
      const uid = user.uid ?? user.id;
      const txSnap = await db
        .collection(`users/${uid}/transactions`)
        .where('type', '==', 'GACHA_PULL')
        .get();
      if (txSnap.empty) continue;
 
      const txDocs = txSnap.docs;
      for (let i = 0; i < txDocs.length; i += 500) {
        const batch = db.batch();
        for (const doc of txDocs.slice(i, i + 500)) {
          batch.delete(doc.ref);
        }
        await batch.commit();
      }
      txDeleted += txDocs.length;
    }
 
    res.json({ success: true, pityReset: pityDocs.length, txDeleted });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all spin history failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Clear Super Shy status ──
router.post('/cleanup/all-supershy', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Clearing all Super Shy status', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('users').where('isSuperShy', '==', true).get();
    const docs = snap.docs;
 
    for (let i = 0; i < docs.length; i += 500) {
      const batch = db.batch();
      for (const doc of docs.slice(i, i + 500)) {
        batch.update(doc.ref, {
          isSuperShy: false,
          superShyExpiry: null,
          superShyTier: null,
          hasClaimedSuperShyTrial: false,
        });
      }
      await batch.commit();
    }
 
    res.json({ success: true, affected: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all Super Shy failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Clear all transactions (all types) ──
router.post('/cleanup/all-transactions', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all transactions', { adminId: req.auth.uniqueId });
 
    const usersSnap = await db.collection('users').orderBy('uid').get();
    const users = usersSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    let deleted = 0;
    for (const user of users) {
      const uid = user.uid ?? user.id;
      const txSnap = await db.collection(`users/${uid}/transactions`).get();
      if (txSnap.empty) continue;
 
      const txDocs = txSnap.docs;
      for (let i = 0; i < txDocs.length; i += 500) {
        const batch = db.batch();
        for (const doc of txDocs.slice(i, i + 500)) {
          batch.delete(doc.ref);
        }
        await batch.commit();
      }
      deleted += txDocs.length;
    }
 
    res.json({ success: true, deleted, usersProcessed: users.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all transactions failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete all suspension appeals ──
router.post('/cleanup/all-appeals', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all suspension appeals', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('suspensionAppeals').get();
    const docs = snap.docs;
 
    for (let i = 0; i < docs.length; i += 500) {
      const batch = db.batch();
      for (const doc of docs.slice(i, i + 500)) {
        batch.delete(doc.ref);
      }
      await batch.commit();
    }
 
    res.json({ success: true, deleted: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all appeals failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Backfill userType for users missing it ──
router.post('/cleanup/backfill-user-type', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Backfilling userType', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('users').limit(5000).get();
    const users = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
    const missing = users.filter((u) => !u.userType && !u.user_type);
 
    if (missing.length === 0) {
      return res.json({ success: true, updated: 0, message: 'All users already have a userType' });
    }
 
    for (let i = 0; i < missing.length; i += 500) {
      const batch = db.batch();
      for (const u of missing.slice(i, i + 500)) {
        batch.update(db.doc(`users/${u.uid ?? u.id}`), { userType: 'MEMBER' });
      }
      await batch.commit();
    }
 
    res.json({ success: true, updated: missing.length });
  } catch (err) {
    log.error('admin-cleanup', 'Backfill userType failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
/** Delete R2 media referenced in conversation messages. Returns count of deleted media. */
async function deleteConversationMedia(convId, CDN_PREFIX) {
  let mediaDeleted = 0;
  const msgsSnap = await db.collection(`conversations/${convId}/messages`).get();
  for (const doc of msgsSnap.docs) {
    const msg = doc.data();
    const urls = msg.imageUrls || [];
    for (const url of urls) {
      if (!url?.startsWith(CDN_PREFIX)) continue;
      try {
        await r2.deleteObject(url.slice(CDN_PREFIX.length));
        mediaDeleted++;
      } catch (err) {
        log.warn('admin-cleanup', 'R2 delete failed', {
          key: url.slice(CDN_PREFIX.length),
          error: err.message,
        });
      }
    }
  }
  return mediaDeleted;
}
 
// ── Delete all private messages (1-on-1 conversations) + R2 media ──
router.post('/cleanup/all-private-messages', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all private messages', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('conversations').limit(5000).get();
    const allConvs = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
    const pms = allConvs.filter((c) => !c.isGroup);
 
    if (pms.length === 0) {
      return res.json({
        success: true,
        deleted: 0,
        mediaDeleted: 0,
        message: 'No private messages found',
      });
    }
 
    const CDN_PREFIX = r2.CDN_URL + '/';
    let mediaDeleted = 0;
 
    for (const conv of pms) {
      mediaDeleted += await deleteConversationMedia(conv.id, CDN_PREFIX);
      await deleteConversation(conv.id);
    }
 
    res.json({ success: true, deleted: pms.length, mediaDeleted });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all private messages failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete all group chats + R2 media ──
router.post('/cleanup/all-group-chats', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all group chats', { adminId: req.auth.uniqueId });
 
    const snap = await db
      .collection('conversations')
      .where('isGroup', '==', true)
      .limit(5000)
      .get();
    const allConvs = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    if (allConvs.length === 0) {
      return res.json({
        success: true,
        deleted: 0,
        mediaDeleted: 0,
        message: 'No group chats found',
      });
    }
 
    const CDN_PREFIX = r2.CDN_URL + '/';
    let mediaDeleted = 0;
 
    for (const conv of allConvs) {
      // Delete group photo from R2
      const photoUrl = conv.groupPhotoUrl || conv.group_photo_url;
      if (photoUrl?.startsWith(CDN_PREFIX)) {
        try {
          await r2.deleteObject(photoUrl.slice(CDN_PREFIX.length));
          mediaDeleted++;
        } catch (err) {
          log.warn('admin-cleanup', 'R2 delete failed', {
            key: photoUrl.slice(CDN_PREFIX.length),
            error: err.message,
          });
        }
      }
      mediaDeleted += await deleteConversationMedia(conv.id, CDN_PREFIX);
      await deleteConversation(conv.id);
    }
 
    res.json({ success: true, deleted: allConvs.length, mediaDeleted });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all group chats failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete all closed rooms + subcollections ──
router.post('/cleanup/all-rooms', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all closed rooms', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('rooms').where('state', '==', 'CLOSED').limit(200).get();
    const closedRooms = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    if (closedRooms.length === 0) {
      return res.json({ success: true, deleted: 0, message: 'No closed rooms found' });
    }
 
    let deleted = 0;
    for (let i = 0; i < closedRooms.length; i += 20) {
      const batch = closedRooms.slice(i, i + 20);
      for (const room of batch) {
        try {
          await deleteRoom(room.id);
          deleted++;
        } catch (err) {
          log.warn('admin-cleanup', 'Room delete failed', { roomId: room.id, error: err.message });
        }
      }
    }
 
    res.json({ success: true, deleted, total: closedRooms.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all rooms failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete all broadcasts ──
router.post('/cleanup/all-broadcasts', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all broadcasts', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('broadcasts').limit(5000).get();
    const docs = snap.docs;
 
    if (docs.length === 0) {
      return res.json({ success: true, deleted: 0, message: 'No broadcasts found' });
    }
 
    for (let i = 0; i < docs.length; i += 500) {
      const batch = db.batch();
      for (const doc of docs.slice(i, i + 500)) {
        batch.delete(doc.ref);
      }
      await batch.commit();
    }
 
    res.json({ success: true, deleted: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all broadcasts failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete all admin audit logs ──
router.post('/cleanup/all-audit-logs', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all audit logs', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('adminAuditLog').limit(5000).get();
    const docs = snap.docs;
 
    if (docs.length === 0) {
      return res.json({ success: true, deleted: 0, message: 'No audit logs found' });
    }
 
    for (let i = 0; i < docs.length; i += 500) {
      const batch = db.batch();
      for (const doc of docs.slice(i, i + 500)) {
        batch.delete(doc.ref);
      }
      await batch.commit();
    }
 
    res.json({ success: true, deleted: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all audit logs failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Clean up destroyed user profiles ──
router.post('/cleanup/destroyed-users', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Cleaning up destroyed user profiles', {
      adminId: req.auth.uniqueId,
    });
 
    const snap = await db.collection('users').limit(5000).get();
    const users = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    const destroyed = users.filter((u) => !u.createdAt);
    const intact = users.length - destroyed.length;
 
    if (destroyed.length === 0) {
      return res.json({ success: true, destroyed: 0, intact, message: 'No destroyed users found' });
    }
 
    for (let i = 0; i < destroyed.length; i += 500) {
      const batch = db.batch();
      for (const u of destroyed.slice(i, i + 500)) {
        batch.delete(db.doc(`users/${u.id}`));
      }
      await batch.commit();
    }
 
    res.json({
      success: true,
      destroyed: destroyed.length,
      intact,
      deletedUids: destroyed.map((u) => u.id),
    });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup destroyed users failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete all device bindings ──
router.post('/cleanup/all-device-bindings', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Deleting all device bindings', { adminId: req.auth.uniqueId });
 
    const snap = await db.collection('deviceBindings').limit(5000).get();
    const docs = snap.docs;
 
    if (docs.length === 0) {
      return res.json({ success: true, deleted: 0, message: 'No device bindings found' });
    }
 
    for (let i = 0; i < docs.length; i += 500) {
      const batch = db.batch();
      for (const doc of docs.slice(i, i + 500)) {
        batch.delete(doc.ref);
      }
      await batch.commit();
    }
 
    res.json({ success: true, deleted: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup all device bindings failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Delete device binding for a specific user ──
router.post('/cleanup/device-binding/:uniqueId', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    const rawId = req.params.uniqueId;
    const numId = Number(rawId);
    // Query both string and number variants — Firestore equality is type-strict
    const uniqueId = Number.isNaN(numId) ? rawId : numId;
    log.info('admin-cleanup', 'Deleting device binding for user', {
      adminId: req.auth.uniqueId,
      targetUniqueId: uniqueId,
    });
    const snap = await db
      .collection('deviceBindings')
      .where('uniqueId', '==', uniqueId)
      .limit(50)
      .get();
    const docs = snap.docs;
 
    if (docs.length === 0) {
      return res.json({ success: true, deleted: 0, message: 'No device bindings for this user' });
    }
 
    const batch = db.batch();
    for (const doc of docs) {
      batch.delete(doc.ref);
    }
    await batch.commit();
 
    res.json({ success: true, deleted: docs.length });
  } catch (err) {
    log.error('admin-cleanup', 'Cleanup device binding failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ══════════════════════════════════════════════════════════════
// STORAGE AUDIT & ORPHAN CLEANUP
// ══════════════════════════════════════════════════════════════
 
// ── R2 folder audit ──
router.get('/storage/audit', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    const folders = [
      'profiles/',
      'covers/',
      'messages/',
      'groups/',
      'evidence/',
      'stickers/',
      'banners/',
    ];
    const results = {};
    let totalFiles = 0;
    let totalBytes = 0;
 
    for (const folder of folders) {
      const objects = await listObjectsWithMeta(folder);
      const count = objects.length;
      let bytes = 0;
      for (const obj of objects) {
        bytes += obj.size || 0;
      }
 
      const name = folder.replace('/', '');
      results[name] = { count, bytes };
      totalFiles += count;
      totalBytes += bytes;
    }
 
    res.json({ folders: results, totalFiles, totalBytes });
  } catch (err) {
    log.error('admin-cleanup', 'Storage audit failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
/** Extract an R2 key from a CDN URL. Returns null if URL doesn't match. */
function extractR2Key(url, CDN_PREFIX) {
  if (!url?.startsWith(CDN_PREFIX)) return null;
  return url.slice(CDN_PREFIX.length);
}
 
/** Collect all referenced R2 keys from Firestore data. */
async function collectReferencedR2Keys(CDN_PREFIX) {
  const referencedKeys = new Set();
  referencedKeys.add('system/shytalk_icon.webp');
 
  // Users
  const usersSnap = await db.collection('users').orderBy('uid').get();
  const USER_URL_FIELDS = [
    'profilePhotoUrl',
    'coverPhotoUrl',
    'preSuspensionProfilePhotoUrl',
    'preSuspensionCoverPhotoUrl',
    'profile_photo_url',
    'cover_photo_url',
    'pre_suspension_profile_photo_url',
    'pre_suspension_cover_photo_url',
  ];
  for (const doc of usersSnap.docs) {
    const userData = doc.data();
    for (const field of USER_URL_FIELDS) {
      const key = extractR2Key(userData[field], CDN_PREFIX);
      if (key) referencedKeys.add(key);
    }
  }
 
  // Conversations
  const convsSnap = await db.collection('conversations').limit(2000).get();
  const convs = convsSnap.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
  for (const conv of convs) {
    const key = extractR2Key(conv.groupPhotoUrl ?? conv.group_photo_url, CDN_PREFIX);
    if (key) referencedKeys.add(key);
  }
 
  // Collect image keys from messages (conversations + rooms)
  await collectImageMessageKeys(convs.slice(0, 30), 'conversations', CDN_PREFIX, referencedKeys);
  const roomsSnap = await db.collection('rooms').limit(200).get();
  const rooms = roomsSnap.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
  await collectImageMessageKeys(rooms.slice(0, 30), 'rooms', CDN_PREFIX, referencedKeys);
 
  // Reports + archive
  const [reportsSnap, archiveSnap] = await Promise.all([
    db.collection('reports').get(),
    db.collection('reportsArchive').get(),
  ]);
  for (const doc of [...reportsSnap.docs, ...archiveSnap.docs]) {
    const urls = doc.data().evidenceUrls ?? doc.data().evidence_urls;
    if (!Array.isArray(urls)) continue;
    for (const url of urls) {
      const key = extractR2Key(url, CDN_PREFIX);
      if (key) referencedKeys.add(key);
    }
  }
 
  // Banners
  const bannersSnap = await db.collection('banners').get();
  for (const doc of bannersSnap.docs) {
    const key = extractR2Key(doc.data().imageUrl ?? doc.data().image_url, CDN_PREFIX);
    if (key) referencedKeys.add(key);
  }
 
  return referencedKeys;
}
 
/** Collect image message keys from a collection's messages subcollections. */
async function collectImageMessageKeys(docs, collectionName, CDN_PREFIX, referencedKeys) {
  for (const item of docs) {
    const msgsSnap = await db
      .collection(`${collectionName}/${item.id}/messages`)
      .where('type', '==', 'IMAGE')
      .limit(200)
      .get();
    for (const doc of msgsSnap.docs) {
      const urls = doc.data().imageUrls ?? doc.data().image_urls;
      if (!Array.isArray(urls)) continue;
      for (const url of urls) {
        const key = extractR2Key(url, CDN_PREFIX);
        if (key) referencedKeys.add(key);
      }
    }
  }
}
 
// ── Smart R2 orphan cleanup ──
router.post('/cleanup/orphaned-storage', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Running orphaned storage cleanup', { adminId: req.auth.uniqueId });
 
    const CDN_PREFIX = r2.CDN_URL + '/';
    const referencedKeys = await collectReferencedR2Keys(CDN_PREFIX);
 
    const folders = [
      'profiles/',
      'covers/',
      'messages/',
      'groups/',
      'evidence/',
      'stickers/',
      'banners/',
    ];
    const summary = {};
    let totalDeleted = 0;
 
    for (const folder of folders) {
      const allKeys = await r2.listObjects(folder);
      const toDelete = allKeys.filter((k) => !referencedKeys.has(k));
      if (toDelete.length > 0) await r2.deleteObjects(toDelete);
      summary[folder.replace('/', '')] = { total: allKeys.length, deleted: toDelete.length };
      totalDeleted += toDelete.length;
    }
 
    res.json({ success: true, summary, totalDeleted });
  } catch (err) {
    log.error('admin-cleanup', 'Orphaned storage cleanup failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Clear all stalkers from all users ──
router.post('/cleanup/all-stalkers', async (req, res) => {
  try {
    Eif (requireAdmin(req, res)) return;
 
    log.info('admin-cleanup', 'Clearing all stalkers', { adminId: req.auth.uniqueId });
 
    const usersSnap = await db.collection('users').orderBy('uid').get();
    let totalDeleted = 0;
    let usersReset = 0;
 
    for (const userDoc of usersSnap.docs) {
      const uid = userDoc.data().uid ?? userDoc.id;
 
      // Delete stalker subcollection
      const stalkersSnap = await db.collection(`users/${uid}/stalkers`).get();
      if (!stalkersSnap.empty) {
        for (let i = 0; i < stalkersSnap.docs.length; i += 500) {
          const batch = db.batch();
          for (const doc of stalkersSnap.docs.slice(i, i + 500)) {
            batch.delete(doc.ref);
          }
          await batch.commit();
        }
        totalDeleted += stalkersSnap.docs.length;
      }
 
      // Reset stalker counts on user doc
      const data = userDoc.data();
      if (
        (data.stalkerCount || 0) > 0 ||
        (data.newStalkerCount || 0) > 0 ||
        data.stalkersLastViewedAt
      ) {
        await db.doc(`users/${uid}`).update({
          stalkerCount: 0,
          newStalkerCount: 0,
          stalkersLastViewedAt: null,
        });
        usersReset++;
      }
    }
 
    log.info('admin-cleanup', 'Stalker cleanup complete', { totalDeleted, usersReset });
    res.json({ success: true, stalkersDeleted: totalDeleted, usersReset });
  } catch (err) {
    log.error('admin-cleanup', 'Stalker cleanup failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// POST /api/cleanup/user-coins/:uniqueId — reset coins for a single user
router.post('/cleanup/user-coins/:uniqueId', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
    await db.doc(`users/${req.params.uniqueId}`).update({ shyCoins: 0 });
    res.json({ success: true });
  } catch (err) {
    log.error('admin-cleanup', 'User coin reset failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// POST /api/cleanup/user-beans/:uniqueId — reset beans for a single user
router.post('/cleanup/user-beans/:uniqueId', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
    await db.doc(`users/${req.params.uniqueId}`).update({ shyBeans: 0 });
    res.json({ success: true });
  } catch (err) {
    log.error('admin-cleanup', 'User bean reset failed', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;