All files / src/routes economy.js

97.44% Statements 878/901
83.83% Branches 534/637
98.5% Functions 66/67
98.64% Lines 799/810

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 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022                                              15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x       15x                                     15x 15x 15x     100x 100x 1x     99x 94x 92x     2x 2x   94x 94x             1649x             27x 27x                                                     26x 20x 20x 20x   1x 1x         1x     1x 1x 1x 1x 1x 3x   1x                                           630x 630x 630x   630x             630x 630x 1x 1x 1x 1x     629x 629x 629x       630x 630x   630x         1x             629x                       125x                     5x 5x                                               630x 630x 630x 629x 629x             629x 629x 2x 2x 2x       627x 627x 627x           627x 627x       629x 629x     629x 630x     629x 2x           627x             1x                 14x 14x 14x   14x 1x               13x   13x 1x   12x   13x   13x           15x 19x 19x 19x 17x 17x         17x 17x 17x   17x 17x 17x 17x 1x   16x 16x 16x 16x 16x 16x           16x 2x     14x 14x 14x   14x         14x 14x   14x 1x 1x 1x 1x             14x                 3x 1x   2x 2x         14x     14x 14x 14x       14x               14x 14x 1x 1x   14x         14x   2x 2x               339x   2x 5x   5x   1x 1x 1x   2x   2x     337x 34x 34x 34x 34x 34x 82x 68x   34x 14x 14x 14x 42x 14x   28x 28x           337x         339x 339x   603x 201x 603x 201x 201x 201x 603x 402x   201x   201x 603x 201x   402x             892x 339x   339x 339x 339x 339x 358x 358x 339x 339x     339x       15x 31x 31x 31x 31x 31x   31x 4x     27x 25x                 25x 25x     25x 1x                     24x 24x 23x   23x 23x     19x           46x   19x     46x 19x     18x 45x   18x 18x 18x 18x     18x 18x         18x 11x 4x 3x 3x 3x       18x 339x 339x             339x   339x 339x   339x 5x   334x       18x   18x 18x     18x 18x 342x   18x     18x   23x 23x         18x 18x 23x 237x 23x 23x 23x     23x                               18x               18x     18x 18x 18x           342x       1x       18x 18x 18x 306x 7x                         7x     18x 342x                       18x   2x 2x         15x 27x 27x 27x 27x 27x   27x 2x 25x 1x 24x 2x   22x             21x 21x 21x 21x   21x 20x 1x 19x         12x 12x   12x 12x 2x       2x     10x 10x 10x 10x 10x 10x     10x 10x 10x 10x 10x 10x 10x 1x   9x         10x     10x     10x 10x 2x 2x 2x 2x                   2x                               10x 10x   10x                                                   10x 9x                         10x   10x   1x 1x         15x 20x 20x 20x 20x 20x   20x 1x 19x 2x   17x           16x 16x 16x   16x     15x     10x 10x   10x 10x 2x       2x     8x 8x   8x 8x 8x 8x               8x   8x 8x 8x 8x 8x 6x 6x     2x 2x           6x     6x     6x 6x 1x 1x 1x 1x                     6x 6x   6x                                                   6x 5x                       6x   6x   1x 1x         15x 26x 26x 26x 26x 26x   26x 2x   24x 1x 23x 2x 21x   20x 19x 18x   18x 18x 17x   17x 17x 17x   17x 17x 11x 11x 11x 1x   6x 6x     15x 15x       15x 15x 15x     23x 23x       15x                       13x 16x 16x               8x     8x 10x 10x 10x 10x 2x       2x         6x 6x 4x 4x 4x 4x 4x 1x   3x     2x 2x 2x 2x         6x 8x 8x 8x 8x   8x 8x     8x 8x 8x   8x 8x                           6x 6x 6x                         6x 6x 1x 1x                     6x 6x                     6x             1x 1x         15x 20x 20x 20x 20x   20x 19x   17x       16x 16x 16x     15x     11x 11x   11x 11x 2x       2x       9x 607x 9x 607x     9x       7x 7x 7x 7x   7x 606x 606x     606x 606x 1x 1x     606x 606x     606x 606x                                 7x 7x   7x   6x 6x     6x 6x   6x           1x 1x 1x     1x 499x   1x   1x 1x 1x 1x 101x   1x         7x 7x 7x 7x 7x 7x   7x                                           7x 7x 1x                   7x   1x 1x         15x 17x 17x 17x 17x   17x 3x     14x 13x 13x                   13x     13x 13x 13x 13x 2x   11x 11x 11x 11x 2x   9x       9x     4x 2x   2x 2x         9x 9x 9x                   9x   1x 1x         15x 34x 34x 34x 34x   34x 2x       32x                   32x 32x               32x 31x 1x       1x       30x   30x 9x 9x       5x 4x 2x   2x     3x             3x     21x           21x     27x 27x 27x       27x 27x 27x 27x   27x 11x 11x   9x             9x 9x 9x 9x           9x                       9x                                 9x 9x                 9x         16x         16x 16x   14x 14x 14x             14x 14x 14x 14x 1x   13x 13x 2x   11x 11x         11x                       11x 11x     3x 1x 1x   2x 2x         11x 11x                 11x   1x 1x         15x 6x 6x                         6x 6x   6x 6x 6x 6x 2x   4x 4x         4x 2x   2x 2x         1x     5x 2x   3x 2x   1x     1x 1x               1x   1x 1x         15x 5x 5x   5x         4x 4x   4x 3x 1x   2x 2x 2x 2x 2x 2x 2x     2x 2x           2x 2x 2x                 2x   1x 1x         15x 7x 7x   6x 6x 6x   6x 3x     3x 2x 1x   1x   1x   1x 1x 1x               1x   1x 1x         15x 12x 12x 12x 11x 9x 9x         1x 1x         15x 5x 5x 5x 5x   5x   4x 1x     4x   4x 13x 4x   1x 1x         15x 4x 4x 4x 1x   3x 3x 2x   1x 1x         15x 16x         16x 16x   15x           7x 2x     5x 6x 5x   1x 1x         15x 13x   13x 12x   12x       11x 1x     10x     10x               10x   10x         10x 10x   1x     1x         15x 297x 297x     15x  
/**
 * Economy routes — daily rewards, gacha, gift sending, bean redemption, purchases.
 *
 * All operations use Firestore as the sole database.
 *
 * POST /api/economy/daily-reward     → Claim daily login reward
 * POST /api/economy/gacha            → Pull gacha (1, 10, or 100)
 * POST /api/economy/gift             → Send gift from backpack
 * POST /api/economy/gift-direct      → Buy and send gift directly
 * POST /api/economy/gift-batch       → Send gifts to multiple recipients
 * POST /api/economy/backpack-send    → Send entire backpack
 * POST /api/economy/redeem-beans     → Redeem beans for coins
 * POST /api/economy/purchase         → Validate in-app purchase
 * POST /api/economy/trial-claim      → Claim Super Shy trial
 * POST /api/economy/trial-activate   → Activate Super Shy trial
 * POST /api/economy/test-coins       → Add test coins (dev)
 * GET  /api/economy/balance          → Get coin/bean balance
 * GET  /api/economy/transactions     → Get transaction history
 * GET  /api/users/:uniqueId/backpack      → Get user's backpack
 * GET  /api/users/:uniqueId/gift-wall     → Get user's gift wall
 * GET  /api/users/:uniqueId/gift-wall/:giftId/senders → Get gift wall senders
 */
 
const crypto = require('node:crypto');
const router = require('express').Router();
const { db, FieldValue } = require('../utils/firebase');
const { generateId, now, todayStr, yesterdayStr } = require('../utils/helpers');
const { requireAdmin, isLiveAdmin } = require('../middleware/auth');
const { requireSameCohort } = require('../middleware/sameCohort');
const { effectiveCohort, cohortFromClaim } = require('../utils/firebase-claims');
const { filterListByCohort } = require('../utils/cohort-filter');
const log = require('../utils/log');
const { verifyProductPurchase, verifySubscription } = require('../utils/playStore');
const { verifyApplePurchase } = require('../utils/appleStore');
const { SUBSCRIPTION_TIERS } = require('../utils/subscriptionTiers');
const { viewerIsBlocked, checkBlockRelationship } = require('../utils/block-check');
 
// ─── Constants ────────────────────────────────────────────────────
 
const DEFAULT_ECONOMY_CONFIG = {
  beanConversionRate: 0.6,
  beanRedeemBonusThreshold: 2000,
  beanRedeemBonusMultiplier: 1.1,
  pullCosts: { 1: 10, 10: 100, 100: 1000 },
  broadcastSendThreshold: 0,
  broadcastWinThreshold: 5000,
  dropRateExponent: 1.5,
  pitySoftStart: 80,
  pityHardLimit: 120,
  pitySoftMaxShift: 0.15,
  pityHighValueThreshold: 5000,
  dailyBase: 50,
  milestoneRewards: { 7: 100, 14: 200, 30: 500, 60: 1000, 90: 2000 },
};
 
// ─── Helpers ──────────────────────────────────────────────────────
 
// In-memory cache for economy config (avoids re-reading Firestore on every request)
let cachedEconomyConfig = null;
let economyConfigCachedAt = 0;
const ECONOMY_CONFIG_TTL = 60_000; // 1 minute
 
async function loadEconomyConfig() {
  const currentTime = Date.now();
  if (cachedEconomyConfig && currentTime - economyConfigCachedAt < ECONOMY_CONFIG_TTL) {
    return cachedEconomyConfig;
  }
 
  const snap = await db.doc('config/economy').get();
  if (snap.exists) {
    cachedEconomyConfig = { ...DEFAULT_ECONOMY_CONFIG, ...snap.data() };
  } else {
    // Doc doesn't exist — write defaults so the Android SDK can read it
    await db.doc('config/economy').set(DEFAULT_ECONOMY_CONFIG);
    cachedEconomyConfig = { ...DEFAULT_ECONOMY_CONFIG };
  }
  economyConfigCachedAt = currentTime;
  return cachedEconomyConfig;
}
 
/**
 * Helper to read a user field with camelCase (new) or snake_case (legacy) fallback.
 */
function userField(user, camel, snake) {
  return user[camel] ?? user[snake] ?? null;
}
 
/**
 * Add a broadcast entry and trim to last 50.
 */
async function addBroadcast(data) {
  const broadcastId = generateId();
  await db.doc(`broadcasts/${broadcastId}`).set({
    id: broadcastId,
    type: data.type,
    senderName: data.senderName,
    senderPhotoUrl: data.senderPhotoUrl || null,
    recipientName: data.recipientName || '',
    giftName: data.giftName,
    giftIconUrl: data.giftIconUrl || '',
    giftCoinValue: data.giftCoinValue,
    quantity: data.quantity || 1,
    timestamp: now(),
  });
 
  // Trim old broadcasts (keep last 50). Pre-fix used
  // `offset(50).limit(100)` which charges Firestore reads for ALL
  // 50 SKIPPED documents on every call — at high gift volume this
  // burns the Spark free-tier 50K-reads/day quota fast (50 reads
  // per broadcast × 1000 broadcasts/day = 50K reads just from
  // trim alone).
  //
  // New strategy:
  //   1. count() aggregate → ~1 billable read regardless of size
  //   2. If count <= 50: skip the trim entirely (no extra cost)
  //   3. If count > 50: read+delete only the OVERFLOW docs (typically 1)
  //
  // Steady-state cost per broadcast: 1 set + 1 count + 1 read + 1
  // delete = 4 ops, down from 51+. Audit H5 (Phase 2A).
  const countSnap = await db.collection('broadcasts').count().get();
  const totalCount = countSnap.data().count;
  const KEEP_LAST = 50;
  if (totalCount <= KEEP_LAST) return;
 
  const overflow = totalCount - KEEP_LAST;
  const oldSnap = await db
    .collection('broadcasts')
    .orderBy('timestamp', 'asc')
    .limit(overflow)
    .get();
  Iif (oldSnap.empty) return;
 
  // Chunk deletes into batches of 500 (Firestore batch limit).
  const docs = oldSnap.docs;
  for (let i = 0; i < docs.length; i += 500) {
    const batch = db.batch();
    const chunk = docs.slice(i, i + 500);
    for (const doc of chunk) {
      batch.delete(doc.ref);
    }
    await batch.commit();
  }
}
 
/**
 * Write a gift to a user's gift wall (upsert receivedCount, update senders).
 *
 * Audit M6 (Phase 2A): receivedCount updates use FieldValue.increment
 * for atomicity. Pre-fix used (read currentCount) → (write current+qty)
 * which lost concurrent updates: two simultaneous gifts to the same
 * recipient/giftId both read receivedCount=5, both wrote 6, true count
 * was 7. Under a room burst-gift scenario this lost gift counts visibly
 * (rankings, profile display).
 *
 * Sender list update is best-effort: it's NOT atomic against itself
 * because senders is an array that needs in-place mutation (find + sort
 * + trim). Two concurrent updates can each lose the OTHER's sender
 * entry. This is documented as known partial-failure for the senders
 * field — the receivedCount remains accurate, which is the
 * primary-display value.
 */
async function updateGiftWall(recipientId, giftId, senderId, quantity, senderCohort) {
  const wallRef = db.doc(`users/${recipientId}/giftWall/${giftId}`);
  const wallSnap = await wallRef.get();
  const wallDoc = wallSnap.exists ? wallSnap.data() : null;
 
  const senders = wallDoc?.senders || [];
 
  // Update or add sender (best-effort — see function header). PR 10:
  // stamp the sender's cohort on the entry so the read path can apply
  // the inner-list filter without a per-entry live lookup. Existing
  // pre-PR-10 entries that lack `cohort` are also backfilled on next
  // send — the legacy-fallback in cohort-filter.js handles the rest.
  const existingSender = senders.find((s) => s.senderId === senderId);
  if (existingSender) {
    existingSender.sendCount = (existingSender.sendCount || 0) + quantity;
    existingSender.lastSentAt = now();
    Eif (senderCohort && !existingSender.cohort) {
      existingSender.cohort = senderCohort;
    }
  } else {
    const entry = { senderId, sendCount: quantity, lastSentAt: now() };
    Eif (senderCohort) entry.cohort = senderCohort;
    senders.push(entry);
  }
 
  // Sort senders by count descending, keep top 50
  senders.sort((a, b) => (b.sendCount || 0) - (a.sendCount || 0));
  const trimmedSenders = senders.slice(0, 50);
 
  if (wallSnap.exists) {
    // Atomic-increment for the count + overwrite for the senders.
    // The senders update is read-modify-write so it's NOT race-safe
    // against itself (documented above), but the count IS race-safe
    // because increment is server-side atomic.
    await wallRef.update({
      giftId,
      receivedCount: FieldValue.increment(quantity),
      senders: trimmedSenders,
    });
  } else {
    // Create path — set is fine here, count starts at quantity.
    await wallRef.set({
      giftId,
      receivedCount: quantity,
      senders: trimmedSenders,
    });
  }
}
 
/**
 * Write a transaction record.
 */
async function writeTransaction(userId, txId, data) {
  await db.doc(`users/${userId}/transactions/${txId}`).set({
    id: txId,
    ...data,
    timestamp: data.timestamp || now(),
  });
}
 
/**
 * Write a room gift message to Firestore.
 */
async function writeRoomGiftMessage(roomId, senderId, senderName, text, giftId, giftIconUrl) {
  const msgId = generateId();
  await db.doc(`rooms/${roomId}/messages/${msgId}`).set({
    id: msgId,
    roomId,
    senderId,
    senderName,
    text,
    type: 'GIFT',
    giftId: giftId || null,
    giftIconUrl: giftIconUrl || '',
    createdAt: now(),
  });
}
 
/**
 * Incrementally update gift rankings when a gift is sent.
 * Replaces the old hourly cron job with real-time updates.
 *
 * Audit M6 (Phase 2A): totalSent uses FieldValue.increment for atomic
 * server-side increment. The rankings array still has the same partial-
 * failure window as updateGiftWall.senders — read-modify-write under
 * concurrent updates can drop entries — but the totalSent counter
 * remains accurate.
 */
async function updateGiftRankings(recipientId, giftId, quantity, recipientCohort) {
  try {
    const rankRef = db.doc(`giftRankings/${giftId}`);
    const rankSnap = await rankRef.get();
    const rankDoc = rankSnap.exists ? rankSnap.data() : {};
    const rankings = rankDoc.rankings || [];
 
    // Find or add recipient in rankings. PR 10: stamp the recipient's
    // cohort so the read path can filter cross-cohort entries without
    // a per-entry live lookup. Pre-PR-10 entries lacking `cohort` are
    // backfilled on next send; legacy-fallback in cohort-filter.js
    // handles unrewritten rows.
    const existing = rankings.find((r) => r.userId === recipientId);
    if (existing) {
      existing.count = (existing.count || 0) + quantity;
      Eif (recipientCohort && !existing.cohort) {
        existing.cohort = recipientCohort;
      }
    } else {
      // Get recipient display info
      const userSnap = await db.doc(`users/${recipientId}`).get();
      const user = userSnap.exists ? userSnap.data() : {};
      const entry = {
        userId: recipientId,
        count: quantity,
        displayName: userField(user, 'displayName', 'display_name') || '',
        profilePhotoUrl: userField(user, 'profilePhotoUrl', 'profile_photo_url') || '',
      };
      Eif (recipientCohort) entry.cohort = recipientCohort;
      rankings.push(entry);
    }
 
    // Sort by count descending, keep top 100
    rankings.sort((a, b) => (b.count || 0) - (a.count || 0));
    const trimmed = rankings.slice(0, 100);
 
    // Re-assign ranks
    trimmed.forEach((r, i) => {
      r.rank = i + 1;
    });
 
    if (rankSnap.exists) {
      await rankRef.update({
        rankings: trimmed,
        totalSent: FieldValue.increment(quantity),
        lastUpdated: now(),
      });
    } else {
      await rankRef.set({
        rankings: trimmed,
        totalSent: quantity,
        lastUpdated: now(),
      });
    }
  } catch (err) {
    log.error('economy', 'Failed to update gift rankings', { error: err.message });
  }
}
 
// ─── Shared gift helpers ─────────────────────────────────────────
// (block-check helpers live in ../utils/block-check — imported above)
 
/** Compute daily reward from config and streak. */
function computeDailyReward(config, newStreak, isSuperShy) {
  const milestoneRewards = config.milestoneRewards || {};
  const rawReward = milestoneRewards[String(newStreak)];
  const isMilestone = String(newStreak) in milestoneRewards;
 
  if (rawReward && typeof rawReward === 'object' && rawReward.type === 'gift') {
    return {
      coinReward: 0,
      giftReward: { giftId: rawReward.giftId, quantity: rawReward.quantity || 1 },
      isMilestone,
    };
  }
 
  let coinReward;
  Iif (typeof rawReward === 'number') {
    coinReward = rawReward;
  } else if (rawReward?.amount) {
    coinReward = rawReward.amount;
  } else {
    coinReward = config.dailyBase;
  }
  if (isSuperShy) coinReward = Math.ceil(coinReward * 1.1);
 
  return { coinReward, giftReward: null, isMilestone };
}
 
// ─── Routes ───────────────────────────────────────────────────────
 
// ── Daily reward ──
router.post('/economy/daily-reward', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const config = await loadEconomyConfig();
    const today = todayStr();
    const yesterday = yesterdayStr();
 
    // Atomic claim per audit H6 — wraps user-read + already-claimed
    // check + user-update + backpack-merge in a Firestore transaction.
    // Pattern matches PRs #485-#488. Sentinel errors caught after.
    const userRef = db.doc(`users/${uniqueId}`);
    const ERR_USER_NOT_FOUND = 'User not found';
    const ERR_ALREADY_CLAIMED = 'Already claimed today';
    let txResult;
    try {
      txResult = await db.runTransaction(async (t) => {
        const userSnap = await t.get(userRef);
        if (!userSnap.exists) {
          throw new Error(ERR_USER_NOT_FOUND);
        }
        const user = userSnap.data();
        const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
        const isSuperShy = userField(user, 'isSuperShy', 'is_super_shy') || false;
        const loginStreak = userField(user, 'loginStreak', 'login_streak') || 0;
        const lastLoginDate = userField(user, 'lastLoginDate', 'last_login_date');
        const lastLoginRewardDate = userField(
          user,
          'lastLoginRewardDate',
          'last_login_reward_date',
        );
 
        if (lastLoginRewardDate === today) {
          throw new Error(ERR_ALREADY_CLAIMED);
        }
 
        const newStreak = lastLoginDate === yesterday ? loginStreak + 1 : 1;
        const reward = computeDailyReward(config, newStreak, isSuperShy);
        const newBalance = shyCoins + reward.coinReward;
 
        const userUpdates = {
          loginStreak: newStreak,
          lastLoginDate: today,
          lastLoginRewardDate: today,
        };
        if (reward.coinReward > 0) userUpdates.shyCoins = newBalance;
        t.update(userRef, userUpdates);
 
        if (reward.giftReward) {
          const bpRef = db.doc(`users/${uniqueId}/backpack/${reward.giftReward.giftId}`);
          const bpSnap = await t.get(bpRef);
          const currentQty = bpSnap.exists ? bpSnap.data().quantity || 0 : 0;
          t.set(bpRef, {
            giftId: reward.giftReward.giftId,
            quantity: currentQty + reward.giftReward.quantity,
            lastAcquired: now(),
          });
        }
 
        return {
          coinReward: reward.coinReward,
          giftReward: reward.giftReward,
          isMilestone: reward.isMilestone,
          newBalance,
          newStreak,
        };
      });
    } catch (txErr) {
      if (txErr.message === ERR_USER_NOT_FOUND) {
        return res.status(404).json({ error: ERR_USER_NOT_FOUND });
      }
      Eif (txErr.message === ERR_ALREADY_CLAIMED) {
        return res.status(409).json({ error: ERR_ALREADY_CLAIMED });
      }
      throw txErr;
    }
 
    const { coinReward, giftReward, isMilestone, newBalance, newStreak } = txResult;
 
    // Transaction record
    const txId = generateId();
    const milestoneSuffix = isMilestone ? ' (milestone)' : '';
    const details = giftReward
      ? `Day ${newStreak} (milestone) — ${giftReward.quantity}x ${giftReward.giftId}`
      : `Day ${newStreak}${milestoneSuffix}`;
 
    await writeTransaction(uniqueId, txId, {
      type: 'DAILY_REWARD',
      amount: giftReward ? giftReward.quantity : coinReward,
      currency: giftReward ? 'GIFT' : 'COINS',
      balanceAfter: newBalance,
      details,
    });
 
    const result = { coinsAwarded: coinReward, newStreak, isMilestone, newBalance };
    if (giftReward) {
      result.giftId = giftReward.giftId;
      result.giftQuantity = giftReward.quantity;
    }
    log.info('economy', 'Daily reward claimed', {
      userId: uniqueId,
      coinReward,
      streak: newStreak,
    });
    res.json(result);
  } catch (err) {
    log.error('economy', 'POST /economy/daily-reward failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Gacha helpers ───────────────────────────────────────────────
 
/** Apply hard or soft pity adjustments to weights. Returns true if hard pity was triggered. */
function applyPitySystem(weights, pity, config, winnableGifts, highValueThreshold) {
  if (pity >= config.pityHardLimit) {
    // Hard pity: zero out low-value gifts
    for (let j = 0; j < winnableGifts.length; j++) {
      if (winnableGifts[j].coinValue < highValueThreshold) weights[j] = 0;
    }
    if (weights.every((w) => w === 0)) {
      // Guarantee the most expensive gift
      let bestIdx = 0;
      for (let j = 1; j < winnableGifts.length; j++) {
        Eif (winnableGifts[j].coinValue > winnableGifts[bestIdx].coinValue) bestIdx = j;
      }
      for (let j = 0; j < weights.length; j++) weights[j] = j === bestIdx ? 1 : 0;
    }
    return true;
  }
 
  if (pity >= config.pitySoftStart) {
    const progress = (pity - config.pitySoftStart) / (config.pityHardLimit - config.pitySoftStart);
    const shift = config.pitySoftMaxShift * progress;
    let lowTotal = 0,
      highTotal = 0;
    for (let j = 0; j < winnableGifts.length; j++) {
      if (winnableGifts[j].coinValue >= highValueThreshold) highTotal += weights[j];
      else lowTotal += weights[j];
    }
    if (lowTotal > 0 && highTotal > 0) {
      const totalWeight = lowTotal + highTotal;
      const shiftAmount = shift * totalWeight;
      for (let j = 0; j < winnableGifts.length; j++) {
        if (winnableGifts[j].coinValue >= highValueThreshold) {
          weights[j] += shiftAmount * (weights[j] / highTotal);
        } else {
          weights[j] -= shiftAmount * (weights[j] / lowTotal);
          Iif (weights[j] < 0) weights[j] = 0;
        }
      }
    }
  }
 
  return false;
}
 
/** Apply luck-based weight adjustments (shift weight from cheapest to others). */
function applyLuckBoost(weights, luck, winnableGifts) {
  const luckBoost = (luck / 100) * 0.05;
  if (luckBoost <= 0) return;
 
  const totalWeight = weights.reduce((s, w) => s + w, 0);
  const shiftAmount = luckBoost * totalWeight;
  const minValue = Math.min(...winnableGifts.map((g) => g.coinValue));
  let cheapTotal = 0,
    expensiveTotal = 0;
  for (let j = 0; j < winnableGifts.length; j++) {
    if (winnableGifts[j].coinValue === minValue) cheapTotal += weights[j];
    else expensiveTotal += weights[j];
  }
  Iif (cheapTotal <= shiftAmount || expensiveTotal <= 0) return;
 
  for (let j = 0; j < winnableGifts.length; j++) {
    if (winnableGifts[j].coinValue === minValue) {
      weights[j] -= shiftAmount * (weights[j] / cheapTotal);
    } else {
      weights[j] += shiftAmount * (weights[j] / expensiveTotal);
    }
  }
}
 
/** Roll a weighted random selection from the gift pool. Returns { gift, fallback }. */
function rollWeightedGift(weights, winnableGifts) {
  const total = weights.reduce((s, w) => s + w, 0);
  Iif (total <= 0) return { gift: winnableGifts[0], fallback: true };
 
  const roll = (require('crypto').randomInt(1_000_000) / 1_000_000) * total;
  let cumulative = 0,
    selectedIndex = 0;
  for (let j = 0; j < weights.length; j++) {
    cumulative += weights[j];
    if (roll <= cumulative) {
      selectedIndex = j;
      break;
    }
  }
  return { gift: winnableGifts[selectedIndex], fallback: false };
}
 
// ── Gacha ──
router.post('/economy/gacha', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const pullCount = body?.pullCount;
    const expectedCost = body?.expectedCost;
 
    if (![1, 10, 100].includes(pullCount)) {
      return res.status(400).json({ error: 'pullCount must be 1, 10, or 100' });
    }
 
    const config = await loadEconomyConfig();
    const pullCosts = config.pullCosts || { 1: 10, 10: 100, 100: 1000 };
    // Audit M3 (Phase 2A): drop the unnecessary `String(pullCount)`
    // coercion. JS object keys are always strings under the hood
    // (numeric literals like `{1: 10}` are stored as `{'1': 10}`),
    // so `pullCosts[pullCount]` resolves identically to
    // `pullCosts[String(pullCount)]`. The audit raised a theoretical
    // "Firestore numeric-key" concern, but Firestore Admin SDK
    // returns plain JS objects with string-only keys regardless of
    // how the doc was originally written. Simpler is better.
    const cost = pullCosts[pullCount];
    Iif (!cost) return res.status(400).json({ error: 'Invalid pull count' });
 
    // Price validation
    if (expectedCost !== null && expectedCost !== undefined && expectedCost !== cost) {
      return res.json({
        priceChanged: true,
        currentPullCosts: pullCosts,
        gifts: [],
        coinsSpent: 0,
        newBalance: 0,
        newPityCounter: 0,
        newLuckScore: 0,
      });
    }
 
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
    const user = userSnap.data();
 
    const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
    if (shyCoins < cost) return res.status(402).json({ error: 'Insufficient coins' });
 
    // Load winnable gifts
    const giftsSnap = await db
      .collection('gifts')
      .where('showOnWheel', '==', true)
      .orderBy('order')
      .limit(16)
      .get();
    const allGifts = giftsSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    Iif (allGifts.length === 0) return res.status(500).json({ error: 'No winnable gifts' });
 
    // Filter to gifts with coinValue > 0
    const winnableGifts = allGifts.filter((g) => (g.coinValue || 0) > 0);
    if (winnableGifts.length === 0) return res.status(500).json({ error: 'No winnable gifts' });
 
    // Compute base weights
    const exponent = config.dropRateExponent;
    const baseWeights = winnableGifts.map((g) => 1 / Math.pow(g.coinValue, exponent));
 
    let pity = userField(user, 'pityCounter', 'pity_counter') || 0;
    let luck = userField(user, 'luckScore', 'luck_score') || 0;
    const highValueThreshold = config.pityHighValueThreshold;
    const results = [];
 
    // Admin-guaranteed first pull
    let guaranteedFirstPull = false;
    const guaranteedGiftId = userField(
      user,
      'guaranteedNextPullGiftId',
      'guaranteed_next_pull_gift_id',
    );
    if (guaranteedGiftId) {
      const guaranteedGift = winnableGifts.find((g) => g.id === guaranteedGiftId);
      if (guaranteedGift) {
        results.push(guaranteedGift);
        guaranteedFirstPull = true;
        pity = guaranteedGift.coinValue >= highValueThreshold ? 0 : pity + 1;
      }
    }
 
    for (let i = guaranteedFirstPull ? 1 : 0; i < pullCount; i++) {
      const weights = [...baseWeights];
      const hardPityTriggered = applyPitySystem(
        weights,
        pity,
        config,
        winnableGifts,
        highValueThreshold,
      );
      applyLuckBoost(weights, luck, winnableGifts);
 
      const { gift, fallback } = rollWeightedGift(weights, winnableGifts);
      results.push(gift);
 
      if (fallback || hardPityTriggered || gift.coinValue >= highValueThreshold) {
        pity = hardPityTriggered || gift.coinValue >= highValueThreshold ? 0 : pity + 1;
      } else {
        pity = pity + 1;
      }
    }
 
    if (pullCount === 100) luck = Math.min(100, luck + 2);
 
    const newBalance = shyCoins - cost;
    const timestamp = now();
 
    // ── Aggregate duplicate gifts so each backpack doc is written once ──
    const giftCounts = {};
    for (const gift of results) {
      giftCounts[gift.id] = (giftCounts[gift.id] || 0) + 1;
    }
    const uniqueGiftIds = Object.keys(giftCounts);
 
    // Fetch existing backpack docs in parallel
    const existingDocs = await Promise.all(
      uniqueGiftIds.map(async (gid) => {
        const snap = await db.doc(`users/${uniqueId}/backpack/${gid}`).get();
        return snap.exists ? snap.data() : null;
      }),
    );
 
    // Build batch writes for backpack + user update in one atomic operation
    const batch = db.batch();
    for (let i = 0; i < uniqueGiftIds.length; i++) {
      const gid = uniqueGiftIds[i];
      const gift = results.find((g) => g.id === gid);
      const bpDoc = existingDocs[i];
      const currentQty = bpDoc?.quantity || 0;
      const expiresAt = gift.expiresAfterDays
        ? timestamp + gift.expiresAfterDays * 86400000
        : bpDoc?.expiresAt || null;
      batch.set(
        db.doc(`users/${uniqueId}/backpack/${gid}`),
        {
          giftId: gid,
          quantity: currentQty + giftCounts[gid],
          lastAcquired: timestamp,
          expiresAt,
          giftName: gift.name,
          coinValue: gift.coinValue,
          iconUrl: gift.iconUrl || gift.icon_url || '',
        },
        { merge: true },
      );
    }
 
    // Include coin deduction in the same batch
    batch.update(db.doc(`users/${uniqueId}`), {
      shyCoins: newBalance,
      pityCounter: pity,
      luckScore: luck,
      guaranteedNextPullGiftId: null,
    });
 
    // Execute atomically — all or nothing
    await batch.commit();
 
    // Transaction record (best-effort — coins already deducted)
    try {
      const gachaTxId = generateId();
      await writeTransaction(uniqueId, gachaTxId, {
        type: 'GACHA_PULL',
        amount: -cost,
        currency: 'COINS',
        balanceAfter: newBalance,
        pullCount,
        details: results.map((g) => g.name).join(', '),
        guaranteed: !!guaranteedFirstPull,
      });
    } catch (err) {
      log.error('economy', 'Failed to write gacha transaction', { uniqueId, error: err.message });
    }
 
    // Broadcast qualifying wins (best-effort)
    try {
      const winThreshold = config.broadcastWinThreshold;
      for (const gift of results) {
        if (gift.coinValue >= winThreshold) {
          await addBroadcast({
            type: 'GACHA_WIN',
            senderName: userField(user, 'displayName', 'display_name') || '',
            senderPhotoUrl: userField(user, 'profilePhotoUrl', 'profile_photo_url'),
            recipientName: '',
            giftName: gift.name,
            giftIconUrl: gift.iconUrl || gift.icon_url || '',
            giftCoinValue: gift.coinValue,
          });
          break; // one broadcast per pull session
        }
      }
    } catch (err) {
      log.error('economy', 'Failed to broadcast gacha win', { uniqueId, error: err.message });
    }
 
    res.json({
      gifts: results.map((g) => ({
        giftId: g.id,
        giftName: g.name,
        coinValue: g.coinValue,
        iconUrl: g.iconUrl || '',
      })),
      coinsSpent: cost,
      newBalance,
      newPityCounter: pity,
      newLuckScore: luck,
      currentPullCosts: pullCosts,
    });
    log.info('economy', `Gacha pull x${pullCount}`, { userId: uniqueId, cost, newBalance });
  } catch (err) {
    log.error('economy', 'POST /economy/gacha failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Send gift from backpack ──
router.post('/economy/gift', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const { recipientId, giftId } = body || {};
    const quantity = Math.max(1, Math.min(9999, Number.parseInt(body?.quantity, 10) || 1));
 
    if (!recipientId || !giftId)
      return res.status(400).json({ error: 'recipientId and giftId required' });
    if (giftId === 'super_shy_trial')
      return res.status(400).json({ error: 'Trial items cannot be transferred' });
    if (uniqueId === recipientId)
      return res.status(400).json({ error: 'Cannot send gift to yourself' });
 
    const [giftSnap, bpSnap, senderSnap, recipientSnap] = await Promise.all([
      db.doc(`gifts/${giftId}`).get(),
      db.doc(`users/${uniqueId}/backpack/${giftId}`).get(),
      db.doc(`users/${uniqueId}`).get(),
      db.doc(`users/${recipientId}`).get(),
    ]);
 
    const gift = giftSnap.exists ? { id: giftSnap.id, ...giftSnap.data() } : null;
    const bpItem = bpSnap.exists ? bpSnap.data() : null;
    const sender = senderSnap.exists ? senderSnap.data() : null;
    const recipient = recipientSnap.exists ? recipientSnap.data() : null;
 
    if (!gift) return res.status(404).json({ error: 'Gift not found' });
    if (!bpItem || (bpItem.quantity || 0) < quantity)
      return res.status(402).json({ error: 'Insufficient items in backpack' });
    if (await requireSameCohort(req, res, recipientId, () => recipient)) return;
 
    // PR 10: snapshot cohorts for write-time stamping on rankings + wall.
    // Sender cohort comes from the JWT claim (single source of truth used
    // by the gate above); recipient cohort comes from their user doc.
    const senderCohort = cohortFromClaim(req);
    const recipientCohort = effectiveCohort(recipient);
 
    const blockError = checkBlockRelationship(sender, recipient, uniqueId, recipientId);
    if (blockError) {
      log.warn('economy', 'Gift blocked: sender/recipient blocked', {
        senderUniqueId: uniqueId,
        recipientUniqueId: recipientId,
      });
      return res.status(403).json({ error: blockError });
    }
 
    const config = await loadEconomyConfig();
    const coinValue = gift.coinValue || gift.coin_value || 0;
    const beanReward = Math.floor(coinValue * config.beanConversionRate * quantity);
    const senderCoins = userField(sender, 'shyCoins', 'shy_coins') || 0;
    const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
    const timestamp = now();
 
    // Decrement backpack atomically via transaction to prevent race conditions
    const bpRef = db.doc(`users/${uniqueId}/backpack/${giftId}`);
    await db.runTransaction(async (t) => {
      const snap = await t.get(bpRef);
      const qty = snap.exists ? snap.data().quantity || 0 : 0;
      Iif (qty < quantity) throw new Error('Insufficient items in backpack');
      const newQty = qty - quantity;
      if (newQty <= 0) {
        t.delete(bpRef);
      } else {
        t.update(bpRef, { quantity: newQty });
      }
    });
 
    // Update recipient gift wall
    await updateGiftWall(recipientId, giftId, uniqueId, quantity, senderCohort);
 
    // Credit beans (atomic increment to avoid race conditions)
    await db.doc(`users/${recipientId}`).update({ shyBeans: FieldValue.increment(beanReward) });
 
    // Room message if sender is in a room
    const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
    if (currentRoomId) {
      const sName = userField(sender, 'displayName', 'display_name') || 'Someone';
      const rName = userField(recipient, 'displayName', 'display_name') || 'Someone';
      const qtyLabel = quantity > 1 ? `${quantity}x ` : '';
      await writeRoomGiftMessage(
        currentRoomId,
        uniqueId,
        sName,
        `${sName} sent ${qtyLabel}${gift.name} to ${rName}`,
        giftId,
        gift.iconUrl || gift.icon_url || '',
      );
 
      // Update last gift event on room doc
      await db.doc(`rooms/${currentRoomId}`).update({
        lastGiftEvent: {
          senderId: uniqueId,
          senderName: sName,
          recipientId,
          recipientName: rName,
          giftId,
          giftName: gift.name,
          coinValue,
          quantity,
          timestamp,
        },
      });
    }
 
    // Transaction records
    const giftSentTxId = generateId();
    const giftReceivedTxId = generateId();
 
    await Promise.all([
      writeTransaction(uniqueId, giftSentTxId, {
        type: 'GIFT_SENT',
        amount: -quantity,
        currency: 'COINS',
        balanceAfter: senderCoins,
        giftId,
        giftName: gift.name,
        recipientId,
        quantity,
        timestamp,
      }),
      writeTransaction(recipientId, giftReceivedTxId, {
        type: 'GIFT_RECEIVED',
        amount: beanReward,
        currency: 'BEANS',
        balanceAfter: recipientBeans + beanReward,
        giftId,
        giftName: gift.name,
        senderId: uniqueId,
        quantity,
        timestamp,
      }),
    ]);
 
    // Broadcast
    if (coinValue >= config.broadcastSendThreshold) {
      await addBroadcast({
        type: 'GIFT_SEND',
        senderName: userField(sender, 'displayName', 'display_name') || '',
        senderPhotoUrl: null,
        recipientName: userField(recipient, 'displayName', 'display_name') || '',
        giftName: gift.name,
        giftIconUrl: gift.iconUrl || gift.icon_url || '',
        giftCoinValue: coinValue,
        quantity,
      });
    }
 
    // Update gift rankings incrementally
    await updateGiftRankings(recipientId, giftId, quantity, recipientCohort);
 
    res.json({ success: true, beanReward, giftName: gift.name, quantity });
  } catch (err) {
    log.error('economy', 'POST /economy/gift failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Send gift directly (buy + send) ──
router.post('/economy/gift-direct', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const { recipientId, giftId } = body || {};
    const quantity = Math.max(1, Math.min(9999, Number.parseInt(body?.quantity, 10) || 1));
 
    if (!recipientId || !giftId)
      return res.status(400).json({ error: 'recipientId and giftId required' });
    if (uniqueId === recipientId)
      return res.status(400).json({ error: 'Cannot send gift to yourself' });
 
    const [giftSnap, senderSnap, recipientSnap] = await Promise.all([
      db.doc(`gifts/${giftId}`).get(),
      db.doc(`users/${uniqueId}`).get(),
      db.doc(`users/${recipientId}`).get(),
    ]);
 
    const gift = giftSnap.exists ? { id: giftSnap.id, ...giftSnap.data() } : null;
    const sender = senderSnap.exists ? senderSnap.data() : null;
    const recipient = recipientSnap.exists ? recipientSnap.data() : null;
 
    if (!gift) return res.status(404).json({ error: 'Gift not found' });
    // UK OSA #17 PR 9 — cohort gate. Collapses missing-recipient and
    // cross-cohort branches into a byte-identical 404 'Not found'.
    if (await requireSameCohort(req, res, recipientId, () => recipient)) return;
 
    // PR 10: snapshot cohorts for write-time stamping.
    const senderCohort = cohortFromClaim(req);
    const recipientCohort = effectiveCohort(recipient);
 
    const blockError = checkBlockRelationship(sender, recipient, uniqueId, recipientId);
    if (blockError) {
      log.warn('economy', 'Gift blocked: sender/recipient blocked', {
        senderUniqueId: uniqueId,
        recipientUniqueId: recipientId,
      });
      return res.status(403).json({ error: blockError });
    }
 
    const coinValue = gift.coinValue || gift.coin_value || 0;
    const totalCost = coinValue * quantity;
 
    const config = await loadEconomyConfig();
    const beanReward = Math.floor(coinValue * config.beanConversionRate * quantity);
    const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
    const timestamp = now();
 
    // Atomic coin deduction. Without the transaction, two concurrent
    // gift-direct requests at the sender's exact balance both pass the
    // pre-check and both call FieldValue.increment(-totalCost), pushing
    // the balance below 0. The transaction reads `shyCoins` fresh and
    // aborts on insufficient funds before decrementing — matches the
    // pattern at /economy/gift-batch (line 1006-1011).
    const senderRef = db.doc(`users/${uniqueId}`);
    let newSenderCoins;
    try {
      newSenderCoins = await db.runTransaction(async (t) => {
        const snap = await t.get(senderRef);
        const coins = snap.exists ? userField(snap.data(), 'shyCoins', 'shy_coins') || 0 : 0;
        if (coins < totalCost) throw new Error('Insufficient coins');
        t.update(senderRef, { shyCoins: FieldValue.increment(-totalCost) });
        return coins - totalCost;
      });
    } catch (txErr) {
      Eif (txErr.message === 'Insufficient coins') {
        return res.status(402).json({ error: 'Insufficient coins' });
      }
      throw txErr;
    }
 
    // Gift wall
    await updateGiftWall(recipientId, giftId, uniqueId, quantity, senderCohort);
 
    // Beans (atomic)
    await db.doc(`users/${recipientId}`).update({ shyBeans: FieldValue.increment(beanReward) });
 
    // Room message
    const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
    if (currentRoomId) {
      const sName = userField(sender, 'displayName', 'display_name') || 'Someone';
      const rName = userField(recipient, 'displayName', 'display_name') || 'Someone';
      const qtyLabel = quantity > 1 ? `${quantity}x ` : '';
      await writeRoomGiftMessage(
        currentRoomId,
        uniqueId,
        sName,
        `${sName} sent ${qtyLabel}${gift.name} to ${rName}`,
        giftId,
        gift.iconUrl || gift.icon_url || '',
      );
    }
 
    // Transactions
    const directSentTxId = generateId();
    const directReceivedTxId = generateId();
 
    await Promise.all([
      writeTransaction(uniqueId, directSentTxId, {
        type: 'GIFT_SENT',
        amount: -totalCost,
        currency: 'COINS',
        balanceAfter: newSenderCoins,
        giftId,
        giftName: gift.name,
        recipientId,
        quantity,
        details: `Sent ${quantity > 1 ? quantity + 'x ' : ''}${gift.name} directly (${totalCost} coins)`,
        timestamp,
      }),
      writeTransaction(recipientId, directReceivedTxId, {
        type: 'GIFT_RECEIVED',
        amount: beanReward,
        currency: 'BEANS',
        balanceAfter: recipientBeans + beanReward,
        giftId,
        giftName: gift.name,
        senderId: uniqueId,
        quantity,
        timestamp,
      }),
    ]);
 
    if (coinValue >= config.broadcastSendThreshold) {
      await addBroadcast({
        type: 'GIFT_SEND',
        senderName: userField(sender, 'displayName', 'display_name') || '',
        recipientName: userField(recipient, 'displayName', 'display_name') || '',
        giftName: gift.name,
        giftIconUrl: gift.iconUrl || gift.icon_url || '',
        giftCoinValue: coinValue,
        quantity,
      });
    }
 
    // Update gift rankings incrementally
    await updateGiftRankings(recipientId, giftId, quantity, recipientCohort);
 
    res.json({ success: true, beanReward, giftName: gift.name, coinsSpent: totalCost, quantity });
  } catch (err) {
    log.error('economy', 'POST /economy/gift-direct failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Send gifts to multiple recipients (batch) ──
router.post('/economy/gift-batch', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const { recipientIds, giftId, fromBackpack } = body || {};
    const quantity = Math.max(1, Math.min(9999, Number.parseInt(body?.quantity, 10) || 1));
 
    if (!recipientIds || !Array.isArray(recipientIds) || recipientIds.length === 0 || !giftId) {
      return res.status(400).json({ error: 'recipientIds array and giftId required' });
    }
    if (giftId === 'super_shy_trial')
      return res.status(400).json({ error: 'Trial items cannot be transferred' });
    if (recipientIds.includes(uniqueId))
      return res.status(400).json({ error: 'Cannot send gift to yourself' });
    if (recipientIds.length > 50) return res.status(400).json({ error: 'Max 50 recipients' });
 
    const giftSnap = await db.doc(`gifts/${giftId}`).get();
    if (!giftSnap.exists) return res.status(404).json({ error: 'Gift not found' });
    const gift = { id: giftSnap.id, ...giftSnap.data() };
 
    const senderSnap = await db.doc(`users/${uniqueId}`).get();
    if (!senderSnap.exists) return res.status(404).json({ error: 'Sender not found' });
    const sender = senderSnap.data();
 
    const coinValue = gift.coinValue || gift.coin_value || 0;
    const totalQty = quantity * recipientIds.length;
    const senderCoins = userField(sender, 'shyCoins', 'shy_coins') || 0;
 
    let bpItem = null;
    if (fromBackpack) {
      const bpSnap = await db.doc(`users/${uniqueId}/backpack/${giftId}`).get();
      bpItem = bpSnap.exists ? bpSnap.data() : null;
      if (!bpItem || (bpItem.quantity || 0) < totalQty)
        return res.status(402).json({ error: 'Insufficient items in backpack' });
    } else {
      const totalCost = coinValue * totalQty;
      if (senderCoins < totalCost) return res.status(402).json({ error: 'Insufficient coins' });
    }
 
    const config = await loadEconomyConfig();
    const timestamp = now();
 
    // Debit sender and credit all recipients in a single transaction
    // to prevent partial failure (sender debited but recipients not credited)
    const bpRef = fromBackpack ? db.doc(`users/${uniqueId}/backpack/${giftId}`) : null;
    const senderRef = db.doc(`users/${uniqueId}`);
    const totalCost = coinValue * totalQty;
 
    // Validate recipient docs exist before starting
    const recipientSnaps = await Promise.all(recipientIds.map((id) => db.doc(`users/${id}`).get()));
    const validRecipients = recipientIds.filter((_, i) => recipientSnaps[i].exists);
    // PR 9 — existence-hiding: same body as the cross-cohort gate's
    // 404 so the attacker can't distinguish "all recipients absent"
    // from "at least one cross-cohort recipient".
    if (validRecipients.length === 0) return res.status(404).json({ error: 'Not found' });
 
    // UK OSA #17 PR 9 — cohort gate (per-recipient, whole-batch refusal
    // on cross-cohort OR missing). We deliberately do NOT silently skip
    // missing recipients here (unlike the block-check loop below): block
    // is a user-controllable signal so leaking via 403 is acceptable,
    // but cohort is an age-derived attribute OSA #17 specifically
    // protects. Skipping missing would let an attacker use a known same-
    // cohort "carrier" alongside a target to binary-test "target exists
    // AND is cross-cohort" via the 200 vs 404 split. So: any non-
    // deliverable recipient (cross-cohort OR missing) refuses the whole
    // batch with a byte-identical 404 'Not found'.
    for (let i = 0; i < recipientIds.length; i++) {
      const recipientData = recipientSnaps[i].exists ? recipientSnaps[i].data() : null;
      if (await requireSameCohort(req, res, recipientIds[i], () => recipientData)) return;
    }
 
    // PR 10: sender cohort is constant across the batch; recipient
    // cohort varies and is computed per-iteration below. Same-cohort
    // is already enforced for every recipient above, so in practice
    // senderCohort === recipientCohort for every iteration — we still
    // pass both explicitly so the stamping logic is straightforward.
    const senderCohort = cohortFromClaim(req);
 
    // Check block relationships — UK OSA requires blocking prevents ALL contact
    for (let i = 0; i < recipientIds.length; i++) {
      Iif (!recipientSnaps[i].exists) continue;
      const recipientData = recipientSnaps[i].data();
      const blockError = checkBlockRelationship(sender, recipientData, uniqueId, recipientIds[i]);
      if (blockError) {
        log.warn('economy', 'Gift blocked: sender/recipient blocked', {
          senderUniqueId: uniqueId,
          recipientUniqueId: recipientIds[i],
        });
        return res.status(403).json({ error: blockError });
      }
    }
 
    // Atomic debit via transaction
    await db.runTransaction(async (t) => {
      if (fromBackpack) {
        const snap = await t.get(bpRef);
        const qty = snap.exists ? snap.data().quantity || 0 : 0;
        Iif (qty < totalQty) throw new Error('Insufficient items in backpack');
        const newQty = qty - totalQty;
        if (newQty <= 0) {
          t.delete(bpRef);
        } else {
          t.update(bpRef, { quantity: newQty });
        }
      } else {
        const snap = await t.get(senderRef);
        const coins = snap.exists ? userField(snap.data(), 'shyCoins', 'shy_coins') || 0 : 0;
        Iif (coins < totalCost) throw new Error('Insufficient coins');
        t.update(senderRef, { shyCoins: FieldValue.increment(-totalCost) });
      }
    });
 
    // Credit recipients (idempotent operations — safe outside transaction)
    for (let i = 0; i < recipientIds.length; i++) {
      const recipientId = recipientIds[i];
      Iif (!recipientSnaps[i].exists) continue;
      const recipient = recipientSnaps[i].data();
      const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
 
      const beanReward = Math.floor(coinValue * config.beanConversionRate * quantity);
      const recipientCohort = effectiveCohort(recipient);
 
      // Gift wall + beans (atomic) + transaction
      await updateGiftWall(recipientId, giftId, uniqueId, quantity, senderCohort);
      await updateGiftRankings(recipientId, giftId, quantity, recipientCohort);
      await db.doc(`users/${recipientId}`).update({ shyBeans: FieldValue.increment(beanReward) });
 
      const recipientTxId = generateId();
      await writeTransaction(recipientId, recipientTxId, {
        type: 'GIFT_RECEIVED',
        amount: beanReward,
        currency: 'BEANS',
        balanceAfter: recipientBeans + beanReward,
        giftId,
        giftName: gift.name,
        senderId: uniqueId,
        quantity,
        timestamp,
      });
    }
 
    // Sender transaction
    const source = fromBackpack ? 'backpack' : 'direct';
    const batchSenderTxId = generateId();
    await writeTransaction(uniqueId, batchSenderTxId, {
      type: 'GIFT_SENT',
      amount: fromBackpack ? 0 : -(coinValue * totalQty),
      currency: 'COINS',
      balanceAfter: fromBackpack ? senderCoins : senderCoins - coinValue * totalQty,
      giftId,
      giftName: gift.name,
      quantity,
      details: `Batch ${source}: ${totalQty}x ${gift.name} to ${recipientIds.length} users`,
      timestamp,
    });
 
    // Room message
    const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
    if (currentRoomId) {
      const sName = userField(sender, 'displayName', 'display_name') || 'Someone';
      await writeRoomGiftMessage(
        currentRoomId,
        uniqueId,
        sName,
        `${sName} sent ${totalQty}x ${gift.name} to ${recipientIds.length} people`,
        giftId,
        gift.iconUrl || gift.icon_url || '',
      );
    }
 
    // Broadcast
    Eif (coinValue >= config.broadcastSendThreshold) {
      await addBroadcast({
        type: 'GIFT_SEND',
        senderName: userField(sender, 'displayName', 'display_name') || '',
        recipientName: `${recipientIds.length} people`,
        giftName: gift.name,
        giftIconUrl: gift.iconUrl || gift.icon_url || '',
        giftCoinValue: coinValue,
        quantity: totalQty,
      });
    }
 
    res.json({
      success: true,
      giftName: gift.name,
      totalSent: totalQty,
      recipientCount: recipientIds.length,
    });
  } catch (err) {
    log.error('economy', 'POST /economy/gift-batch failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Send entire backpack ──
router.post('/economy/backpack-send', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const { recipientId } = body || {};
 
    if (!recipientId) return res.status(400).json({ error: 'recipientId required' });
    if (uniqueId === recipientId) return res.status(400).json({ error: 'Cannot send to yourself' });
 
    const [senderSnap, recipientSnap] = await Promise.all([
      db.doc(`users/${uniqueId}`).get(),
      db.doc(`users/${recipientId}`).get(),
    ]);
    const sender = senderSnap.exists ? senderSnap.data() : null;
    const recipient = recipientSnap.exists ? recipientSnap.data() : null;
    if (!sender) return res.status(404).json({ error: 'Sender not found' });
    // UK OSA #17 PR 9 — cohort gate. Collapses missing-recipient and
    // cross-cohort branches into a byte-identical 404 'Not found'.
    if (await requireSameCohort(req, res, recipientId, () => recipient)) return;
 
    // PR 10: snapshot cohorts for write-time stamping on each item.
    const senderCohort = cohortFromClaim(req);
    const recipientCohort = effectiveCohort(recipient);
 
    const blockError = checkBlockRelationship(sender, recipient, uniqueId, recipientId);
    if (blockError) {
      log.warn('economy', 'Gift blocked: sender/recipient blocked', {
        senderUniqueId: uniqueId,
        recipientUniqueId: recipientId,
      });
      return res.status(403).json({ error: blockError });
    }
 
    // Get backpack items (excluding trial items)
    const backpackSnap = await db.collection(`users/${uniqueId}/backpack`).get();
    const backpackItems = backpackSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
    const sendableItems = backpackItems.filter(
      (item) => item.giftId !== 'super_shy_trial' && (item.quantity || 0) > 0,
    );
 
    if (sendableItems.length === 0) return res.status(400).json({ error: 'Backpack is empty' });
 
    // For each backpack item, we need gift metadata. If denormalized on the bp doc, use it.
    // Otherwise, look up the gift.
    const config = await loadEconomyConfig();
    const timestamp = now();
    let totalItemsSent = 0;
    let totalBeanReward = 0;
 
    for (const item of sendableItems) {
      const qty = item.quantity || 0;
      totalItemsSent += qty;
 
      // Get coin value from backpack doc or gift catalog
      let coinVal = item.coinValue;
      if (coinVal === null || coinVal === undefined) {
        const giftDocSnap = await db.doc(`gifts/${item.giftId}`).get();
        coinVal = giftDocSnap.exists ? giftDocSnap.data().coinValue || 0 : 0;
      }
 
      const beanReward = Math.floor(coinVal * config.beanConversionRate * qty);
      totalBeanReward += beanReward;
 
      // Gift wall + rankings
      await updateGiftWall(recipientId, item.giftId, uniqueId, qty, senderCohort);
      await updateGiftRankings(recipientId, item.giftId, qty, recipientCohort);
    }
 
    // Atomic: bean credit + ALL backpack deletes in the same batch.
    // Without this, a transient Firestore error between the bean
    // credit (recipient already credited) and the backpack delete
    // (sender's items still present) leaves a state where the
    // sender can re-send their backpack and DOUBLE-CREDIT the
    // recipient. Audit H8 (Phase 2A).
    //
    // Firestore batch limit is 500 ops. The bean update is 1 op;
    // we have N delete ops. If N+1 > 500 we must split — but in
    // that case we sacrifice atomicity and accept the original
    // partial-failure surface. We pick the bean-credit batch to
    // include the FIRST chunk of deletes so any single chunk
    // failure leaves no partial state for chunk #1. Subsequent
    // chunks remain best-effort.
    const FIRESTORE_BATCH_LIMIT = 500;
    const BATCH_FIRST_CHUNK_LIMIT = FIRESTORE_BATCH_LIMIT - 1; // reserve 1 for bean update
 
    if (sendableItems.length <= BATCH_FIRST_CHUNK_LIMIT) {
      // Common case: small backpack. Single atomic batch.
      const batch = db.batch();
      batch.update(db.doc(`users/${recipientId}`), {
        shyBeans: FieldValue.increment(totalBeanReward),
      });
      for (const item of sendableItems) {
        batch.delete(db.doc(`users/${uniqueId}/backpack/${item.giftId}`));
      }
      await batch.commit();
    } else {
      // Rare case: very large backpack > 499 distinct gift items.
      // First batch contains the bean credit + first 499 deletes (all
      // atomic — covers the credit-without-delete failure mode for
      // the bulk of items). Remaining deletes follow in 500-op batches.
      const firstChunk = sendableItems.slice(0, BATCH_FIRST_CHUNK_LIMIT);
      const firstBatch = db.batch();
      firstBatch.update(db.doc(`users/${recipientId}`), {
        shyBeans: FieldValue.increment(totalBeanReward),
      });
      for (const item of firstChunk) {
        firstBatch.delete(db.doc(`users/${uniqueId}/backpack/${item.giftId}`));
      }
      await firstBatch.commit();
 
      for (let i = BATCH_FIRST_CHUNK_LIMIT; i < sendableItems.length; i += FIRESTORE_BATCH_LIMIT) {
        const batch = db.batch();
        const chunk = sendableItems.slice(i, i + FIRESTORE_BATCH_LIMIT);
        for (const item of chunk) {
          batch.delete(db.doc(`users/${uniqueId}/backpack/${item.giftId}`));
        }
        await batch.commit();
      }
    }
 
    // Transactions
    const senderCoins = userField(sender, 'shyCoins', 'shy_coins') || 0;
    const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
    const bpSentTxId = generateId();
    const bpReceivedTxId = generateId();
    const senderName = userField(sender, 'displayName', 'display_name') || 'user';
    const recipientName = userField(recipient, 'displayName', 'display_name') || 'user';
 
    await Promise.all([
      writeTransaction(uniqueId, bpSentTxId, {
        type: 'BACKPACK_SENT',
        amount: 0,
        currency: 'ITEMS',
        balanceAfter: senderCoins,
        totalItemsSent,
        details: `Sent entire backpack (${totalItemsSent} items) to ${recipientName}`,
        timestamp,
      }),
      writeTransaction(recipientId, bpReceivedTxId, {
        type: 'BACKPACK_RECEIVED',
        amount: totalBeanReward,
        currency: 'BEANS',
        balanceAfter: recipientBeans + totalBeanReward,
        totalItemsReceived: totalItemsSent,
        details: `Received entire backpack (${totalItemsSent} items) from ${senderName}`,
        timestamp,
      }),
    ]);
 
    // Room message
    const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
    if (currentRoomId) {
      await writeRoomGiftMessage(
        currentRoomId,
        uniqueId,
        senderName,
        `${senderName} sent their entire backpack (${totalItemsSent} items) to ${recipientName}`,
        null,
        '',
      );
    }
 
    res.json({ success: true, totalItemsSent, totalBeanReward });
  } catch (err) {
    log.error('economy', 'POST /economy/backpack-send failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Redeem beans ──
router.post('/economy/redeem-beans', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const amount = body?.amount;
 
    if (!amount || typeof amount !== 'number' || amount < 1) {
      return res.status(400).json({ error: 'amount must be a positive number' });
    }
 
    const config = await loadEconomyConfig();
    const hasBonus = amount >= config.beanRedeemBonusThreshold;
    const coins = hasBonus ? Math.floor(amount * config.beanRedeemBonusMultiplier) : amount;
 
    // Atomic bean→coin conversion. Without the transaction, two
    // concurrent redeem requests at the user's exact bean balance
    // both pass the `shyBeans < amount` check and both decrement,
    // pushing balance below 0. Coins would also be over-credited.
    // The transaction reads beans fresh inside the tx; aborts on
    // insufficient; performs the swap atomically.
    //
    // Audit C2 (Phase 2A): /economy/redeem-beans race condition.
    const userRef = db.doc(`users/${uniqueId}`);
    let newBeans;
    let newCoins;
    try {
      ({ newBeans, newCoins } = await db.runTransaction(async (t) => {
        const snap = await t.get(userRef);
        if (!snap.exists) {
          throw new Error('User not found');
        }
        const data = snap.data();
        const beans = userField(data, 'shyBeans', 'shy_beans') || 0;
        const coinsNow = userField(data, 'shyCoins', 'shy_coins') || 0;
        if (beans < amount) {
          throw new Error('Insufficient beans');
        }
        t.update(userRef, {
          shyBeans: FieldValue.increment(-amount),
          shyCoins: FieldValue.increment(coins),
        });
        return { newBeans: beans - amount, newCoins: coinsNow + coins };
      }));
    } catch (txErr) {
      if (txErr.message === 'User not found') {
        return res.status(404).json({ error: 'User not found' });
      }
      Eif (txErr.message === 'Insufficient beans') {
        return res.status(402).json({ error: 'Insufficient beans' });
      }
      throw txErr;
    }
 
    const bonusPct = Math.round((config.beanRedeemBonusMultiplier - 1) * 100);
    const redeemTxId = generateId();
    await writeTransaction(uniqueId, redeemTxId, {
      type: 'BEAN_REDEEM',
      amount: coins,
      currency: 'COINS',
      balanceAfter: newCoins,
      details: hasBonus
        ? `Redeemed ${amount} beans (${bonusPct}% bonus)`
        : `Redeemed ${amount} beans`,
    });
 
    res.json({ coinsReceived: coins, newCoinBalance: newCoins, newBeanBalance: newBeans });
  } catch (err) {
    log.error('economy', 'POST /economy/redeem-beans failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Validate purchase ──
router.post('/economy/purchase', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const { productId, purchaseToken, isSubscription, platform } = body || {};
 
    if (!productId || !purchaseToken)
      return res.status(400).json({ error: 'productId and purchaseToken required' });
 
    // Default to Google Play for backward-compat — every Android client
    // historically omitted the field. iOS clients MUST send `platform: 'apple'`.
    const purchasePlatform = platform === 'apple' ? 'apple' : 'google';
 
    // Deterministic receipt doc ID derived from purchaseToken.
    // SHA-256 collisions are infeasible; any two requests with the
    // SAME token write to the SAME doc, making the receipt set
    // idempotent at the storage layer. Combined with the inside-tx
    // existence check below, this closes the replay race window
    // that the previous where-query duplicate check could not.
    //
    // Audit C4 (Phase 2A): /economy/purchase replay race.
    const receiptId = crypto.createHash('sha256').update(String(purchaseToken)).digest('hex');
    const receiptRef = db.doc(`purchaseReceipts/${receiptId}`);
 
    // Pre-flight (cheap fast-path on already-processed tokens).
    // The authoritative duplicate check happens inside the
    // transaction below — this just avoids paying the verification
    // cost (network call to Google/Apple) for tokens we've already
    // seen. A race between this check and the tx is fine: the tx
    // will catch the duplicate and reject.
    const existingSnap = await receiptRef.get();
    if (existingSnap.exists) {
      log.warn('economy', 'Duplicate purchase token rejected (pre-flight)', {
        userId: uniqueId,
        productId,
      });
      return res.status(409).json({ error: 'Purchase already processed' });
    }
 
    // Verify purchase with the appropriate store (Google Play or Apple App Store)
    const packageName = 'com.shyden.shytalk';
    let verification;
    if (process.env.NODE_ENV === 'production') {
      try {
        if (purchasePlatform === 'apple') {
          // iOS sends `Transaction.jwsRepresentation` as `purchaseToken`.
          // verifyApplePurchase enforces bundleId, productId, revocation,
          // and (for subs) expiry — see appleStore.js.
          verification = await verifyApplePurchase(productId, purchaseToken, !!isSubscription);
        } else if (isSubscription) {
          verification = await verifySubscription(packageName, productId, purchaseToken);
        } else {
          verification = await verifyProductPurchase(packageName, productId, purchaseToken);
        }
      } catch (verifyErr) {
        log.warn('economy', 'Purchase verification rejected', {
          userId: uniqueId,
          productId,
          platform: purchasePlatform,
          isSubscription: !!isSubscription,
          error: verifyErr.message,
        });
        return res.status(403).json({ error: 'Purchase verification failed' });
      }
    } else {
      log.warn('economy', 'Skipping purchase verification in non-production environment', {
        userId: uniqueId,
        productId,
        platform: purchasePlatform,
        isSubscription: !!isSubscription,
      });
      verification = { orderId: 'dev-unverified' };
    }
 
    const orderId = verification.orderId || verification.latestOrderId || null;
    const timestamp = now();
    const userRef = db.doc(`users/${uniqueId}`);
 
    // Sentinels for tx-internal aborts. Caught after the tx and
    // mapped to the appropriate HTTP status.
    const ERR_DUPLICATE = 'Purchase already processed';
    const ERR_UNKNOWN_SUB = 'Unknown subscription product';
    const ERR_USER_NOT_FOUND = 'User not found';
    const ERR_UNKNOWN_PKG = 'Unknown coin package';
 
    if (isSubscription) {
      const sub = SUBSCRIPTION_TIERS[productId];
      if (!sub) return res.status(400).json({ error: ERR_UNKNOWN_SUB });
 
      const expiry = sub.days ? timestamp + sub.days * 86400000 : null;
 
      // Atomic: re-check receipt + write receipt + grant subscription.
      // Firestore transactions retry on contention; a concurrent
      // request that wins the race will populate the receipt before
      // this tx's t.get() sees it, causing this attempt to abort
      // with ERR_DUPLICATE on retry.
      try {
        await db.runTransaction(async (t) => {
          const rcptSnap = await t.get(receiptRef);
          Iif (rcptSnap.exists) {
            throw new Error(ERR_DUPLICATE);
          }
          // Persist tier + days for refund-time reversal (see
          // pre-fix comment): refund reads from receipt rather
          // than re-deriving from mutable SUBSCRIPTION_TIERS map.
          t.set(receiptRef, {
            userId: uniqueId,
            productId,
            purchaseToken,
            platform: purchasePlatform,
            isSubscription: true,
            createdAt: timestamp,
            verified: true,
            orderId,
            tierGranted: sub.tier,
            daysGranted: sub.days,
          });
          t.update(userRef, {
            isSuperShy: true,
            superShyExpiry: expiry,
            superShyTier: sub.tier,
          });
        });
      } catch (txErr) {
        if (txErr.message === ERR_DUPLICATE) {
          log.warn('economy', 'Duplicate purchase rejected (tx)', {
            userId: uniqueId,
            productId,
          });
          return res.status(409).json({ error: ERR_DUPLICATE });
        }
        throw txErr;
      }
 
      const subTxId = generateId();
      await writeTransaction(uniqueId, subTxId, {
        type: 'SUBSCRIPTION',
        amount: 0,
        currency: 'COINS',
        balanceAfter: 0,
        details: `Super Shy ${sub.tier}`,
        timestamp,
      });
 
      return res.json({ success: true, tier: sub.tier });
    }
 
    // Coin package — look up package OUTSIDE the tx (read-only,
    // stable). Fail fast on unknown package before opening the tx.
    const pkgSnap = await db
      .collection('coinPackages')
      .where('productId', '==', productId)
      .limit(1)
      .get();
    const pkg = pkgSnap.empty ? null : { id: pkgSnap.docs[0].id, ...pkgSnap.docs[0].data() };
    if (!pkg) return res.status(404).json({ error: ERR_UNKNOWN_PKG });
 
    const coinsGranted = pkg.coins || 0;
    const bonusCoinsGranted = pkg.bonusCoins || 0;
    const totalCoins = coinsGranted + bonusCoinsGranted;
 
    // Atomic: re-check receipt + read user + write receipt + grant
    // coins, all in one transaction. Reading the user inside the tx
    // ensures `newBalance` reflects post-grant state consistently
    // even under concurrent purchases.
    let newBalance;
    try {
      newBalance = await db.runTransaction(async (t) => {
        const rcptSnap = await t.get(receiptRef);
        if (rcptSnap.exists) {
          throw new Error(ERR_DUPLICATE);
        }
        const userSnap = await t.get(userRef);
        if (!userSnap.exists) {
          throw new Error(ERR_USER_NOT_FOUND);
        }
        const user = userSnap.data();
        const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
        // Persist actual granted amounts on the receipt so the refund
        // handler can reverse the original entitlement even if
        // `coinPackages` is later mutated (price changes, promotional
        // bonus weekends, deprecated SKUs).
        t.set(receiptRef, {
          userId: uniqueId,
          productId,
          purchaseToken,
          platform: purchasePlatform,
          isSubscription: false,
          createdAt: timestamp,
          verified: true,
          orderId,
          coinsGranted,
          bonusCoinsGranted,
        });
        t.update(userRef, { shyCoins: FieldValue.increment(totalCoins) });
        return shyCoins + totalCoins;
      });
    } catch (txErr) {
      if (txErr.message === ERR_DUPLICATE) {
        log.warn('economy', 'Duplicate purchase rejected (tx)', { userId: uniqueId, productId });
        return res.status(409).json({ error: ERR_DUPLICATE });
      }
      Eif (txErr.message === ERR_USER_NOT_FOUND) {
        return res.status(404).json({ error: ERR_USER_NOT_FOUND });
      }
      throw txErr;
    }
 
    const purchaseTxId = generateId();
    await writeTransaction(uniqueId, purchaseTxId, {
      type: 'PURCHASE',
      amount: totalCoins,
      currency: 'COINS',
      balanceAfter: newBalance,
      details: `${pkg.coins} + ${pkg.bonusCoins || 0} bonus coins`,
      timestamp,
    });
 
    res.json({ success: true, coinsAdded: totalCoins, newBalance });
  } catch (err) {
    log.error('economy', 'POST /economy/purchase failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Super Shy trial claim ──
router.post('/economy/trial-claim', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
 
    // Atomic claim: read+set+backpack-write in a single transaction.
    // Without this, two concurrent trial-claim requests both read
    // hasClaimedSuperShyTrial=false, both pass the guard, both write
    // hasClaimedSuperShyTrial=true and add the trial item to backpack
    // (set with no merge → quantity:1 each time, so backpack ends up
    // with quantity:1 either way, but the user has effectively claimed
    // a paid feature unlock TWICE — duplicate audit log entries, double
    // analytics trigger, and potentially double-applied entitlement on
    // the client side which observes both writes).
    //
    // Audit C3 (Phase 2A): /economy/trial-claim TOCTOU race.
    const userRef = db.doc(`users/${uniqueId}`);
    const backpackRef = db.doc(`users/${uniqueId}/backpack/super_shy_trial`);
    let shyCoins;
    try {
      shyCoins = await db.runTransaction(async (t) => {
        const snap = await t.get(userRef);
        if (!snap.exists) {
          throw new Error('User not found');
        }
        const data = snap.data();
        const hasClaimed = userField(
          data,
          'hasClaimedSuperShyTrial',
          'has_claimed_super_shy_trial',
        );
        if (hasClaimed) {
          throw new Error('Trial already claimed');
        }
        t.update(userRef, { hasClaimedSuperShyTrial: true });
        t.set(backpackRef, {
          giftId: 'super_shy_trial',
          quantity: 1,
          giftName: 'Super Shy Trial',
        });
        return userField(data, 'shyCoins', 'shy_coins') || 0;
      });
    } catch (txErr) {
      if (txErr.message === 'User not found') {
        return res.status(404).json({ error: 'User not found' });
      }
      if (txErr.message === 'Trial already claimed') {
        return res.status(409).json({ error: 'Trial already claimed' });
      }
      throw txErr;
    }
 
    const trialClaimTxId = generateId();
    await writeTransaction(uniqueId, trialClaimTxId, {
      type: 'TRIAL_CLAIM',
      amount: 0,
      currency: 'COINS',
      balanceAfter: shyCoins,
      details: 'Claimed 30 days of Super Shy',
    });
 
    res.json({ success: true });
  } catch (err) {
    log.error('economy', 'POST /economy/trial-claim failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Super Shy trial activate ──
router.post('/economy/trial-activate', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
 
    const [userSnap, bpSnap] = await Promise.all([
      db.doc(`users/${uniqueId}`).get(),
      db.doc(`users/${uniqueId}/backpack/super_shy_trial`).get(),
    ]);
 
    const user = userSnap.exists ? userSnap.data() : null;
    const bpItem = bpSnap.exists ? bpSnap.data() : null;
 
    if (!user) return res.status(404).json({ error: 'User not found' });
    if (!bpItem || (bpItem.quantity || 0) < 1)
      return res.status(402).json({ error: 'No trial item in backpack' });
 
    const timestamp = now();
    const thirtyDays = 30 * 24 * 60 * 60 * 1000;
    const currentExpiry = userField(user, 'superShyExpiry', 'super_shy_expiry') || 0;
    const baseTime = Math.max(currentExpiry, timestamp);
    const newExpiry = baseTime + thirtyDays;
    const currentTier = userField(user, 'superShyTier', 'super_shy_tier');
    const newTier = currentTier && currentTier !== 'trial' ? currentTier : 'trial';
 
    // Remove trial from backpack and activate
    await db.doc(`users/${uniqueId}/backpack/super_shy_trial`).delete();
    await db.doc(`users/${uniqueId}`).update({
      isSuperShy: true,
      superShyExpiry: newExpiry,
      superShyTier: newTier,
    });
 
    const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
    const trialActivateTxId = generateId();
    await writeTransaction(uniqueId, trialActivateTxId, {
      type: 'TRIAL_ACTIVATE',
      amount: 0,
      currency: 'COINS',
      balanceAfter: shyCoins,
      details: 'Activated 30 days of Super Shy',
      timestamp,
    });
 
    res.json({ success: true, newTier, newExpiry });
  } catch (err) {
    log.error('economy', 'POST /economy/trial-activate failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Test coins (admin only) ──
router.post('/economy/test-coins', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const amount = body?.amount;
 
    if (!amount || typeof amount !== 'number' || amount <= 0 || amount > 100000) {
      return res.status(400).json({ error: 'amount must be 1-100000' });
    }
 
    const userSnap = await db.doc(`users/${uniqueId}`).get();
    if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
    const user = userSnap.data();
 
    const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
 
    await db.doc(`users/${uniqueId}`).update({ shyCoins: FieldValue.increment(amount) });
 
    const newBalance = shyCoins + amount;
    const testTxId = generateId();
    await writeTransaction(uniqueId, testTxId, {
      type: 'PURCHASE',
      amount,
      currency: 'COINS',
      balanceAfter: newBalance,
      details: `Test purchase (+${amount} coins)`,
    });
 
    res.json({ success: true, coinsAdded: amount, newBalance });
  } catch (err) {
    log.error('economy', 'POST /economy/test-coins failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Balance ──
router.get('/economy/balance', async (req, res) => {
  try {
    const uniqueId = req.auth.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();
    res.json({
      coins: userField(user, 'shyCoins', 'shy_coins') || 0,
      beans: userField(user, 'shyBeans', 'shy_beans') || 0,
    });
  } catch (err) {
    log.error('economy', 'GET /economy/balance failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Transactions ──
router.get('/economy/transactions', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const limit = Math.min(Number.parseInt(req.query.limit, 10) || 50, 200);
    const filterType = req.query.type;
 
    let query = db.collection(`users/${uniqueId}/transactions`);
 
    if (filterType) {
      query = query.where('type', '==', filterType);
    }
 
    query = query.orderBy('timestamp', 'desc').limit(limit);
 
    const snap = await query.get();
    const results = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
    res.json(results);
  } catch (err) {
    log.error('economy', 'GET /economy/transactions failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Backpack ──
router.get('/users/:uniqueId/backpack', async (req, res) => {
  try {
    const isAdmin = req.auth.token?.admin;
    if (String(req.auth.uniqueId) !== req.params.uniqueId && !isAdmin) {
      return res.status(403).json({ error: "Cannot access another user's backpack" });
    }
    const snap = await db.collection(`users/${req.params.uniqueId}/backpack`).get();
    const results = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
    res.json(results);
  } catch (err) {
    log.error('economy', 'GET /users/:uniqueId/backpack failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Gift wall ──
router.get('/users/:uniqueId/gift-wall', async (req, res) => {
  try {
    // PR 10 — outer cohort gate. The target's gift wall is itself a
    // user-owned list, so cross-cohort callers get the byte-identical
    // 404 existence-hider. Target doc is fetched once and shared with
    // the block check below.
    const targetSnap = await db.doc(`users/${req.params.uniqueId}`).get();
    const target = targetSnap.exists ? targetSnap.data() : null;
 
    if (await requireSameCohort(req, res, req.params.uniqueId, () => target)) return;
 
    // C7 (block-list integrity): a user who has been blocked by the
    // target must not be able to see the target's gift wall. Runs
    // AFTER the cohort gate so 403 only fires for same-cohort blocks
    // (cross-cohort would have already returned 404).
    if (target && viewerIsBlocked(req.auth.uniqueId, target)) {
      return res.status(403).json({ error: 'Cannot view content of users who have blocked you' });
    }
 
    const snap = await db.collection(`users/${req.params.uniqueId}/giftWall`).get();
    const results = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
    res.json(results);
  } catch (err) {
    log.error('economy', 'GET /users/:uniqueId/gift-wall failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Gift wall senders ──
router.get('/users/:uniqueId/gift-wall/:giftId/senders', async (req, res) => {
  try {
    // PR 10 — outer cohort gate (mirrors the gift-wall handler above).
    const targetSnap = await db.doc(`users/${req.params.uniqueId}`).get();
    const target = targetSnap.exists ? targetSnap.data() : null;
 
    if (await requireSameCohort(req, res, req.params.uniqueId, () => target)) return;
 
    // C7: same block check as the parent gift-wall list — the sender
    // list is a strict subset of gift-wall data.
    if (target && viewerIsBlocked(req.auth.uniqueId, target)) {
      return res.status(403).json({ error: 'Cannot view content of users who have blocked you' });
    }
 
    const docSnap = await db
      .doc(`users/${req.params.uniqueId}/giftWall/${req.params.giftId}`)
      .get();
    const senders = docSnap.exists ? docSnap.data().senders || [] : [];
 
    // PR 10 — inner cohort filter. Admin (live-verified) bypasses the
    // filter to retain moderation visibility. Otherwise each sender's
    // cohort comes from a stamped `cohort` field (PR 10 write-time) or
    // falls back to a per-entry users/<id> lookup for legacy rows. The
    // deleted-user case is dropped explicitly so a deleted account
    // can't leak as a same-minor-cohort entry to minor callers.
    const isAdmin = req?.auth?.token?.admin === true && Boolean(await isLiveAdmin(req.auth.uid));
 
    const filtered = isAdmin
      ? senders.slice()
      : await filterListByCohort(senders, cohortFromClaim(req), 'senderId');
 
    // Sort by sendCount descending
    filtered.sort((a, b) => (b.sendCount || 0) - (a.sendCount || 0));
    res.json(filtered);
  } catch (err) {
    log.error('economy', 'GET /users/:uniqueId/gift-wall/:giftId/senders failed', {
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// Test helper to reset in-memory config cache
router._resetConfigCache = () => {
  cachedEconomyConfig = null;
  economyConfigCachedAt = 0;
};
 
module.exports = router;