All files / src/utils idbCache.ts

73.25% Statements 608/830
69.29% Branches 88/127
87.75% Functions 43/49
73.25% Lines 608/830

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 15831x 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 632x 632x 12x 12x 11x 11x 11x   11x 11x 11x   11x 11x 11x 11x   11x 11x 11x 11x 11x 11x   11x 11x 11x   11x 11x 11x   11x 11x 11x 11x   11x 11x 11x   11x 11x 11x 11x   11x 11x 11x 11x 12x 12x 632x 632x   43x 43x 43x   12x 12x 12x   51x 51x 51x   1x 1x 1x   1x                     1x 1x 8x 8x 8x 8x 8x           8x   1x                         1x 1x 4x 4x 4x 4x 4x           4x   1x                     1x 20x 20x 2x 2x 20x 15x 15x 3x 3x   1x                         1x 1x 11x 11x 11x 20x 20x 5x 20x 15x 15x 20x 11x 11x   1x                             1x 1x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 7x 7x 1x 1x 7x     7x   1x                               1x 1x 32x 32x 32x 32x 32x 27x 27x 32x         32x   1x 1x 1x   1x                 1x 1x 22x 22x 22x 22x 22x 22x           22x   1x                     1x 1x 119x 119x 119x 119x   119x   119x 119x 119x 1x 1x 1x 1x 1x 1x 1x 1x 1x   119x 119x         119x   1x                         1x 1x 2x 2x   2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x           2x   1x                 1x 1x 38x 38x 38x 38x         38x   1x 1x 1x   1x                       1x 1x 3x   3x 3x 3x 3x 1x 1x 1x 1x 3x             3x   1x                       1x 1x 2x 2x   2x 2x 2x 2x   2x 2x 2x                           2x 2x 2x 2x 2x   2x 2x           2x   1x                   1x 1x                       1x                         1x 1x                             4x 4x 4x 4x             4x   1x                 1x 1x                     1x 1x 1x   1x                       1x 1x 5x   5x 5x 5x 5x 2x 2x 2x 2x 5x             5x   1x                       1x 1x 5x 5x   5x 5x 5x 5x   5x 5x 5x               5x 5x 5x 5x 5x   5x 5x           5x   1x                       1x 1x 2x 2x 2x 2x           2x   1x                         1x 1x                             1x                 1x 1x 2x 2x 2x 2x           2x   1x 1x 1x   1x                     1x 1x 14x   14x 14x 14x 13x 14x           14x   1x                       1x 1x 14x 14x   14x 14x 14x 14x 14x         14x   1x                   1x 1x 27x 27x 27x 27x 27x 25x 25x 27x 27x           27x   1x                     1x 1x                               1x                 1x 1x 14x 14x 14x 14x         14x   1x 1x 1x   1x                                   1x 1x 10x 10x 10x 10x 10x           10x   1x                             1x 1x                     1x                       1x 1x                     1x 1x 1x   1x                           1x 1x 73x 73x 73x 73x       73x   1x                                 1x 1x 46x 46x 46x 46x     46x   1x                           1x 1x 2x 2x 2x 2x             2x   1x                       1x 1x 2x 2x 2x             2x   1x                       1x 1x 26x 26x 26x 26x         26x   1x 1x 1x   1x                       1x 1x 34x 34x 34x 34x 34x           34x   1x                           1x 1x 19x 19x 19x 19x 19x 19x 19x 19x         19x   1x                             1x 1x 34x 34x   1x 1x 1x   1x                               1x 1x 33x 33x 33x 33x 33x   33x 33x 33x 33x 33x 33x 27x 33x 3x 3x 3x 3x 3x   33x 33x 33x     33x   1x                   1x 1x 18x 18x 18x 18x 18x       18x   1x                   1x 1x 1x 1x 1x 1x 1x     1x   1x                 1x 1x 17x 17x 17x 17x 17x     17x                             1x                               1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   20x 20x 20x 20x 20x 2x 2x               2x   20x 20x 20x           2x 2x 2x   1x 1x 1x   1x                     1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x     15x   1x 1x 1x   1x                   1x 1x 8x 8x 8x 8x       8x   1x                     1x 1x 2x 2x 2x 2x     2x  
import { storage } from '@/../config.json';
import { IDB_STORE, type IdbStore } from '@/constants/common';
import type { ExcludedProductsMap } from '@/helpers/excludedProducts';
import type { ChemicalDbRecord, OshaChemical } from '@/helpers/oshaChemicalDb';
import { Logger } from '@/utils/Logger';
import { type DBSchema, type IDBPDatabase, openDB } from 'idb';
import { getErrorMessage } from '@/helpers/exceptions';
 
/**
 * Custom event name dispatched when search results are cleared.
 * Consumers listen for this via `window.addEventListener` to replace
 * the former `cstorage.onChanged` pattern for `search_results`.
 * @category Utils
 */
export const IDB_SEARCH_RESULTS_CLEARED = 'idb:search-results-cleared';
 
/**
 * Custom event name dispatched when supplier stats are updated.
 * Consumers listen for this to live-refresh stats during searches.
 * @category Utils
 */
export const IDB_SUPPLIER_STATS_UPDATED = 'idb:supplier-stats-updated';
 
/**
 * Custom event name dispatched when the cached exports change (added, deleted,
 * or cleared). The export-history list listens for this to live-refresh.
 * @category Utils
 */
export const IDB_EXPORTS_UPDATED = 'idb:exports-updated';
 
const logger = new Logger('idbCache');
 
const DB_NAME = 'chempal';
const DB_VERSION = 8;
 
/** Single-row key used by the `chemical_db` store. */
const CHEMICAL_DB_KEY = 'current';
 
/** Single-row key used by the `app_meta` store (mirrors the `"current"` pattern of `search_results`). */
const APP_META_KEY = 'current';
// Cache-capacity caps live in config.json alongside the other build-time tunables.
const MAX_SUPPLIER_CACHE_ENTRIES = storage.maxSupplierCacheEntries;
const MAX_HISTORY_ENTRIES = storage.maxHistoryEntries;
// Exports are capped by BOTH a record count and a total byte budget; the oldest
// are evicted first when either is exceeded (see `putExport`).
const MAX_EXPORT_ENTRIES = storage.maxExportEntries;
const MAX_EXPORT_CACHE_BYTES = storage.maxExportsCacheBytes;
 
/**
 * A cached spreadsheet export: the generated `.xlsx` Blob plus the metadata the
 * export-history list displays. Stored in the `exports` object store.
 * @category Utils
 */
export interface ExportRecord {
  /** Unique id; also the object-store key. */
  id: string;
  /** Epoch milliseconds the export was created; drives newest-first order + eviction. */
  createdAt: number;
  /** Suggested download filename, e.g. `chempal-export-acetone-2026-07-21-140322.xlsx`. */
  filename: string;
  /** Originating search query, if any. */
  query?: string;
  /** Whether the export covered all results or only the filtered view. */
  scope: 'all' | 'filtered';
  /** Number of top-level products exported (excludes variant subrows). */
  rowCount: number;
  /** Byte size of {@link ExportRecord.blob}; summed for the total-size cap. */
  sizeBytes: number;
  /** The generated `.xlsx` file. */
  blob: Blob;
}
 
interface ChemPalDBSchema extends DBSchema {
  search_results: {
    key: string;
    value: {
      id: string;
      data: Product[];
      query?: string;
    };
  };
  search_history: {
    key: number;
    value: SearchHistoryEntry;
  };
  supplier_query_cache: {
    key: string;
    value: {
      cacheKey: string;
      data: unknown[];
      __cacheMetadata: {
        cachedAt: number;
        version: number;
        query: string;
        supplier: string;
        supplierModule: string;
        resultCount: number;
        limit: number;
      };
    };
    indexes: {
      cachedAt: number;
    };
  };
  supplier_product_data_cache: {
    key: string;
    value: {
      cacheKey: string;
      data: Record<string, unknown>;
      timestamp: number;
    };
    indexes: {
      timestamp: number;
    };
  };
  supplier_stats: {
    key: string;
    value: {
      dateKey: string;
      suppliers: Record<string, SupplierDayStats>;
    };
  };
  excluded_products: {
    key: string;
    value: {
      id: string;
      map: ExcludedProductsMap;
    };
  };
  price_history: {
    key: string;
    value: PriceHistoryEntry;
    indexes: {
      productKey: string;
    };
  };
  app_meta: {
    key: string;
    value: {
      id: string;
      appVersion: string;
      updatedAt: number;
    };
  };
  exports: {
    key: string;
    value: ExportRecord;
    indexes: {
      createdAt: number;
    };
  };
  chemical_db: {
    key: string;
    value: ChemicalDbRecord;
  };
}
 
let dbPromise: Promise<IDBPDatabase<ChemPalDBSchema>> | null = null;
 
/**
 * Returns a singleton promise to the opened IndexedDB database.
 * Creates object stores on first open via the `upgrade` callback.
 */
function getDB(): Promise<IDBPDatabase<ChemPalDBSchema>> {
  if (!dbPromise) {
    dbPromise = openDB<ChemPalDBSchema>(DB_NAME, DB_VERSION, {
      upgrade(db) {
        if (!db.objectStoreNames.contains(IDB_STORE.SEARCH_RESULTS)) {
          db.createObjectStore(IDB_STORE.SEARCH_RESULTS, { keyPath: 'id' });
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.SEARCH_HISTORY)) {
          db.createObjectStore(IDB_STORE.SEARCH_HISTORY, { keyPath: 'timestamp' });
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.SUPPLIER_QUERY_CACHE)) {
          const sqc = db.createObjectStore(IDB_STORE.SUPPLIER_QUERY_CACHE, { keyPath: 'cacheKey' });
          sqc.createIndex('cachedAt', '__cacheMetadata.cachedAt');
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE)) {
          const spdc = db.createObjectStore(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE, {
            keyPath: 'cacheKey',
          });
          spdc.createIndex('timestamp', 'timestamp');
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.SUPPLIER_STATS)) {
          db.createObjectStore(IDB_STORE.SUPPLIER_STATS, { keyPath: 'dateKey' });
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.EXCLUDED_PRODUCTS)) {
          db.createObjectStore(IDB_STORE.EXCLUDED_PRODUCTS, { keyPath: 'id' });
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.PRICE_HISTORY)) {
          const ph = db.createObjectStore(IDB_STORE.PRICE_HISTORY, { keyPath: 'id' });
          ph.createIndex('productKey', 'productKey');
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.APP_META)) {
          db.createObjectStore(IDB_STORE.APP_META, { keyPath: 'id' });
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.EXPORTS)) {
          const exports = db.createObjectStore(IDB_STORE.EXPORTS, { keyPath: 'id' });
          exports.createIndex('createdAt', 'createdAt');
        }
 
        if (!db.objectStoreNames.contains(IDB_STORE.CHEMICAL_DB)) {
          db.createObjectStore(IDB_STORE.CHEMICAL_DB, { keyPath: 'id' });
        }
      },
    });
  }
  return dbPromise;
}
 
function emitSearchResultsCleared(): void {
  window.dispatchEvent(new CustomEvent(IDB_SEARCH_RESULTS_CLEARED));
}
 
function emitSupplierStatsUpdated(): void {
  window.dispatchEvent(new CustomEvent(IDB_SUPPLIER_STATS_UPDATED));
}
 
function emitExportsUpdated(): void {
  window.dispatchEvent(new CustomEvent(IDB_EXPORTS_UPDATED));
}
 
/* -------------------------------------------------------------------------- */
/*                            Search Results                                  */
/* -------------------------------------------------------------------------- */
 
/**
 * Reads the persisted search results. The row is stored under a single
 * `"current"` key, so this is one read. See {@link getSearchResultsRecord} when
 * the originating query is needed too.
 * @category Utils
 * @returns The persisted products, or `[]` when nothing is stored or the read fails.
 * @example
 * ```ts
 * const products = await getSearchResults(); // => [{ id: "…", title: "Acetone" }]
 * ```
 * @source
 */
export async function getSearchResults(): Promise<Product[]> {
  try {
    const db = await getDB();
    const record = await db.get(IDB_STORE.SEARCH_RESULTS, 'current');
    return record?.data ?? [];
  } catch (error) {
    logger.error(`Failed to get search results from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return [];
  }
}
 
/**
 * Reads the persisted `search_results` row as a whole, returning both the product
 * `data` and the `query` that produced it. Use this (instead of {@link getSearchResults})
 * when the caller also needs the originating query — e.g. to rehydrate the results
 * header label so it stays in sync with the persisted results.
 * @category Utils
 * @returns The persisted results and query. `data` is `[]` and `query` is `undefined`
 * when no row exists (or the row predates the `query` field).
 * @example
 * ```ts
 * await getSearchResultsRecord(); // { data: [{ id: "A", ... }], query: "acetone" }
 * ```
 * @source
 */
export async function getSearchResultsRecord(): Promise<{ data: Product[]; query?: string }> {
  try {
    const db = await getDB();
    const record = await db.get(IDB_STORE.SEARCH_RESULTS, 'current');
    return { data: record?.data ?? [], query: record?.query };
  } catch (error) {
    logger.error(`Failed to get search results record from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return { data: [] };
  }
}
 
/**
 * Derives a stable per-product identity used to detect duplicates, independent
 * of the positional `_id`. Prefers the supplier-stable `cacheKey`, then the real
 * product `id`, and finally the `supplier`+`url` pair.
 * @param product - The product to key.
 * @returns A string identity unique to the underlying product.
 * @example
 * ```ts
 * productIdentity({ cacheKey: "P000805666", ... }); // "ck:P000805666"
 * ```
 * @source
 */
function productIdentity(product: Product): string {
  if (product.cacheKey) {
    return `ck:${product.cacheKey}`;
  }
  if (product.id != null) {
    return `id:${String(product.id)}`;
  }
  return `su:${product.supplier}:${product.url}`;
}
 
/**
 * Finds product identities that appear more than once, keyed by
 * `productIdentity` (ignoring the positional `_id`). This is detection, not
 * repair: the same product appearing twice means the search almost certainly ran
 * twice, so callers surface it rather than silently removing the duplicates.
 * @category Utils
 * @param results - The products to scan.
 * @returns The duplicated identities (empty when every product is unique).
 * @example
 * ```ts
 * findDuplicateProductIds([{ id: "A" }, { id: "A" }, { id: "B" }]); // ["id:A"]
 * ```
 * @source
 */
export function findDuplicateProductIds(results: Product[]): string[] {
  const seen = new Set<string>();
  const duplicates = new Set<string>();
  for (const product of results) {
    const key = productIdentity(product);
    if (seen.has(key)) {
      duplicates.add(key);
    } else {
      seen.add(key);
    }
  }
  return [...duplicates];
}
 
/**
 * Persists the current search results (and the query that produced them) to the
 * single `"current"` `search_results` row. Storing the `query` alongside `data`
 * keeps the two in lockstep, so the results header can rehydrate the query even
 * when the transient session copy is gone. Duplicate products are logged (not
 * removed); an empty result set dispatches {@link IDB_SEARCH_RESULTS_CLEARED}.
 * @category Utils
 * @param results - The products to persist.
 * @param query - The originating search query. Omitted for callers with no query
 * context; stored as `undefined` in that case.
 * @example
 * ```ts
 * await setSearchResults([{ id: "A", ... }], "acetone");
 * ```
 * @source
 */
export async function setSearchResults(results: Product[], query?: string): Promise<void> {
  try {
    const db = await getDB();
    // Detect (do NOT silently remove) duplicates before persisting. The same
    // product appearing twice means the search almost certainly fired twice —
    // surface that loudly instead of masking the underlying double-search bug.
    const duplicateIds = findDuplicateProductIds(results);
    if (duplicateIds.length > 0) {
      logger.warn('Duplicate products in search results — the search likely fired twice', {
        duplicateCount: duplicateIds.length,
        duplicateIds,
        total: results.length,
      });
    }
    await db.put(IDB_STORE.SEARCH_RESULTS, { id: 'current', data: results, query });
    if (results.length === 0) {
      emitSearchResultsCleared();
    }
  } catch (error) {
    logger.error(`Failed to set search results in IndexedDB: ${getErrorMessage(error)}`, { error });
  }
}
 
/**
 * Clears all persisted search results from IndexedDB.
 * By default this dispatches {@link IDB_SEARCH_RESULTS_CLEARED} so listeners
 * (e.g. the App) can react to an explicit, user-initiated clear. Pass
 * `{ notify: false }` to clear silently — used when resetting the store at the
 * start of a new search, where firing the event would bounce the user off the
 * results panel.
 * @category Utils
 * @param options - Clear behavior.
 * - `notify` - Whether to dispatch {@link IDB_SEARCH_RESULTS_CLEARED} (default `true`).
 * @example
 * ```ts
 * await clearSearchResults();                  // clears + notifies listeners
 * await clearSearchResults({ notify: false }); // clears silently
 * ```
 * @source
 */
export async function clearSearchResults(options: { notify?: boolean } = {}): Promise<void> {
  const { notify = true } = options;
  try {
    const db = await getDB();
    await db.delete(IDB_STORE.SEARCH_RESULTS, 'current');
    if (notify) {
      emitSearchResultsCleared();
    }
  } catch (error) {
    logger.error(`Failed to clear search results from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                            Search History                                  */
/* -------------------------------------------------------------------------- */
 
/**
 * Reads every search-history entry, newest first.
 * @category Utils
 * @returns History entries sorted by descending timestamp, or `[]` on failure.
 * @example
 * ```ts
 * const history = await getSearchHistory(); // => [{ query: "acetone", timestamp: 172… }]
 * ```
 * @source
 */
export async function getSearchHistory(): Promise<SearchHistoryEntry[]> {
  try {
    const db = await getDB();
    const all = await db.getAll(IDB_STORE.SEARCH_HISTORY);
    // Return sorted newest-first
    return all.sort((a, b) => b.timestamp - a.timestamp);
  } catch (error) {
    logger.error(`Failed to get search history from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return [];
  }
}
 
/**
 * Appends a search-history entry, evicting the oldest rows once the store
 * exceeds `maxHistoryEntries` from config.json.
 * @category Utils
 * @param entry - The entry to store; its `timestamp` is the primary key.
 * @returns Resolves once the write (and any eviction) completes.
 * @example
 * ```ts
 * await addSearchHistoryEntry({ query: "acetone", timestamp: Date.now(), resultCount: 12 });
 * ```
 * @source
 */
export async function addSearchHistoryEntry(entry: SearchHistoryEntry): Promise<void> {
  try {
    const db = await getDB();
    const tx = db.transaction(IDB_STORE.SEARCH_HISTORY, 'readwrite');
    const store = tx.objectStore(IDB_STORE.SEARCH_HISTORY);
 
    await store.put(entry);
 
    // Enforce max entries — delete oldest if over limit
    const count = await store.count();
    if (count > MAX_HISTORY_ENTRIES) {
      const excess = count - MAX_HISTORY_ENTRIES;
      let cursor = await store.openCursor();
      let deleted = 0;
      while (cursor && deleted < excess) {
        await cursor.delete();
        deleted++;
        cursor = await cursor.continue();
      }
    }
 
    await tx.done;
  } catch (error) {
    logger.error(`Failed to add search history entry to IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/**
 * Backfills the result count on an existing history entry, which is written
 * before the search finishes and so starts out without one. No-ops when the
 * entry is gone (e.g. already evicted).
 * @category Utils
 * @param timestamp - Primary key of the entry to update.
 * @param count - The final number of results for that search.
 * @returns Resolves once the update completes.
 * @example
 * ```ts
 * await updateSearchHistoryResultCount(1712345678901, 42);
 * ```
 * @source
 */
export async function updateSearchHistoryResultCount(
  timestamp: number,
  count: number,
): Promise<void> {
  try {
    const db = await getDB();
    const tx = db.transaction(IDB_STORE.SEARCH_HISTORY, 'readwrite');
    const store = tx.objectStore(IDB_STORE.SEARCH_HISTORY);
    const entry = await store.get(timestamp);
    if (entry) {
      entry.resultCount = count;
      await store.put(entry);
    }
    await tx.done;
  } catch (error) {
    logger.error(
      `Failed to update search history result count in IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
  }
}
 
/**
 * Removes every search-history entry.
 * @category Utils
 * @returns Resolves once the store is empty.
 * @example
 * ```ts
 * await clearSearchHistory();
 * ```
 * @source
 */
export async function clearSearchHistory(): Promise<void> {
  try {
    const db = await getDB();
    await db.clear(IDB_STORE.SEARCH_HISTORY);
  } catch (error) {
    logger.error(`Failed to clear search history from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                        Supplier Query Cache                                */
/* -------------------------------------------------------------------------- */
 
/**
 * Reads one supplier query-cache entry — a cached result set keyed by
 * query+supplier — along with its cache metadata.
 * @category Utils
 * @param cacheKey - The composite query+supplier cache key.
 * @returns The cached entry, or `undefined` on a miss or read failure.
 * @example
 * ```ts
 * const hit = await getSupplierQueryCacheEntry("acetone|Loudwolf");
 * hit?.__cacheMetadata.cachedAt; // => 1712345678901
 * ```
 * @source
 */
export async function getSupplierQueryCacheEntry(
  cacheKey: string,
): Promise<CachedData<unknown> | undefined> {
  try {
    const db = await getDB();
    const record = await db.get(IDB_STORE.SUPPLIER_QUERY_CACHE, cacheKey);
    if (!record) return undefined;
    return {
      data: record.data,
      __cacheMetadata: record.__cacheMetadata,
    };
  } catch (error) {
    logger.error(
      `Failed to get supplier query cache entry from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
    return undefined;
  }
}
 
/**
 * Writes a supplier query-cache entry, evicting the least recently cached row
 * first when the store is at `storage.maxSupplierCacheEntries` capacity.
 * @category Utils
 * @param cacheKey - The composite query+supplier cache key.
 * @param entry - The result set plus its `__cacheMetadata`.
 * @returns Resolves once the write (and any eviction) completes.
 * @example
 * ```ts
 * await putSupplierQueryCacheEntry("acetone|Loudwolf", { data: [], __cacheMetadata: meta });
 * ```
 * @source
 */
export async function putSupplierQueryCacheEntry(
  cacheKey: string,
  entry: CachedData<unknown>,
): Promise<void> {
  try {
    const db = await getDB();
    const tx = db.transaction(IDB_STORE.SUPPLIER_QUERY_CACHE, 'readwrite');
    const store = tx.objectStore(IDB_STORE.SUPPLIER_QUERY_CACHE);
 
    // Evict oldest if at capacity
    const count = await store.count();
    if (count >= MAX_SUPPLIER_CACHE_ENTRIES) {
      const index = store.index('cachedAt');
      const cursor = await index.openCursor();
      if (cursor) {
        logger.debug('Evicting oldest supplier query cache entry', {
          key: cursor.value.cacheKey,
          age:
            Math.round((Date.now() - cursor.value.__cacheMetadata.cachedAt) / (60 * 60 * 1000)) +
            ' hours',
        });
        await cursor.delete();
      }
    }
 
    await store.put({
      cacheKey,
      data: entry.data,
      __cacheMetadata: entry.__cacheMetadata,
    });
 
    await tx.done;
  } catch (error) {
    logger.error(
      `Failed to put supplier query cache entry in IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
  }
}
 
/**
 * Removes a single supplier query-cache entry, e.g. when it fails TTL validation.
 * @category Utils
 * @param cacheKey - The composite query+supplier cache key to delete.
 * @returns Resolves once the row is gone.
 * @example
 * ```ts
 * await deleteSupplierQueryCacheEntry("acetone|Loudwolf");
 * ```
 * @source
 */
export async function deleteSupplierQueryCacheEntry(cacheKey: string): Promise<void> {
  try {
    const db = await getDB();
    await db.delete(IDB_STORE.SUPPLIER_QUERY_CACHE, cacheKey);
  } catch (error) {
    logger.error(
      `Failed to delete supplier query cache entry from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
  }
}
 
/**
 * Read every entry in the supplier **query** cache — the cached search-result
 * sets keyed by query+supplier. Intended for manual inspection from the debug
 * console; each record carries its `cacheKey`, the dumped `data`, and its
 * `__cacheMetadata` (query, supplier, `cachedAt`, etc.). Returns `[]` on failure.
 * @category Utils
 * @returns All stored query-cache records, or `[]` when the read fails.
 * @example
 * ```ts
 * const entries = await getAllSupplierQueryCacheEntries();
 * entries[0].__cacheMetadata.query; // => "sodium chloride"
 * ```
 * @source
 */
export async function getAllSupplierQueryCacheEntries(): Promise<
  Array<{
    cacheKey: string;
    data: unknown[];
    __cacheMetadata: {
      cachedAt: number;
      version: number;
      query: string;
      supplier: string;
      supplierModule: string;
      resultCount: number;
      limit: number;
    };
  }>
> {
  try {
    const db = await getDB();
    return await db.getAll(IDB_STORE.SUPPLIER_QUERY_CACHE);
  } catch (error) {
    logger.error(
      `Failed to get all supplier query cache entries from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
    return [];
  }
}
 
/**
 * Empties the supplier query cache, forcing the next search to refetch.
 * @category Utils
 * @returns Resolves once the store is empty.
 * @example
 * ```ts
 * await clearSupplierQueryCache();
 * ```
 * @source
 */
export async function clearSupplierQueryCache(): Promise<void> {
  try {
    const db = await getDB();
    await db.clear(IDB_STORE.SUPPLIER_QUERY_CACHE);
  } catch (error) {
    logger.error(`Failed to clear supplier query cache from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                     Supplier Product Data Cache                            */
/* -------------------------------------------------------------------------- */
 
/**
 * Reads one entry from the supplier **product data** cache, which holds
 * per-product detail fetched lazily after a search.
 * @category Utils
 * @param cacheKey - The product-level cache key.
 * @returns The cached product data and its timestamp, or `undefined` on a miss.
 * @example
 * ```ts
 * const entry = await getSupplierProductDataCacheEntry("Loudwolf|SKU-1");
 * entry?.timestamp; // => 1712345678901
 * ```
 * @source
 */
export async function getSupplierProductDataCacheEntry(
  cacheKey: string,
): Promise<CachedProductEntry | undefined> {
  try {
    const db = await getDB();
    const record = await db.get(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE, cacheKey);
    if (!record) return undefined;
    return {
      data: record.data,
      timestamp: record.timestamp,
    };
  } catch (error) {
    logger.error(
      `Failed to get supplier product data cache entry from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
    return undefined;
  }
}
 
/**
 * Writes a supplier product-data cache entry, evicting the oldest row first
 * when the store is at `storage.maxSupplierCacheEntries` capacity.
 * @category Utils
 * @param cacheKey - The product-level cache key.
 * @param entry - The product data and the timestamp it was fetched.
 * @returns Resolves once the write (and any eviction) completes.
 * @example
 * ```ts
 * await putSupplierProductDataCacheEntry("Loudwolf|SKU-1", { data, timestamp: Date.now() });
 * ```
 * @source
 */
export async function putSupplierProductDataCacheEntry(
  cacheKey: string,
  entry: CachedProductEntry,
): Promise<void> {
  try {
    const db = await getDB();
    const tx = db.transaction(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE, 'readwrite');
    const store = tx.objectStore(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE);
 
    // Evict oldest if at capacity
    const count = await store.count();
    if (count >= MAX_SUPPLIER_CACHE_ENTRIES) {
      const index = store.index('timestamp');
      const cursor = await index.openCursor();
      if (cursor) {
        await cursor.delete();
      }
    }
 
    await store.put({
      cacheKey,
      data: entry.data,
      timestamp: entry.timestamp,
    });
 
    await tx.done;
  } catch (error) {
    logger.error(
      `Failed to put supplier product data cache entry in IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
  }
}
 
/**
 * Deletes a single product-detail cache entry by its identity key. Used to evict
 * one product from the cache (e.g. the "Remove Product from Cache" context-menu
 * action) so its detail data is re-fetched fresh the next time it is surfaced,
 * without touching the visible results.
 * @category Utils
 * @param cacheKey - The product-detail cache key, from `getProductIdentityKey`.
 * @example
 * ```ts
 * await deleteSupplierProductDataCacheEntry(getProductIdentityKey(product.cacheKey, product.supplier));
 * ```
 * @source
 */
export async function deleteSupplierProductDataCacheEntry(cacheKey: string): Promise<void> {
  try {
    const db = await getDB();
    await db.delete(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE, cacheKey);
  } catch (error) {
    logger.error(
      `Failed to delete supplier product data cache entry from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
  }
}
 
/**
 * Read every entry in the supplier **product-detail** cache — the enriched
 * per-product data keyed by product identity. Intended for manual inspection
 * from the debug console; each record carries its `cacheKey`, the cached `data`,
 * and its last-access `timestamp`. Returns `[]` on failure.
 * @category Utils
 * @returns All stored product-detail records, or `[]` when the read fails.
 * @example
 * ```ts
 * const entries = await getAllSupplierProductDataCacheEntries();
 * entries.length; // => number of cached product-detail rows
 * ```
 * @source
 */
export async function getAllSupplierProductDataCacheEntries(): Promise<
  Array<{ cacheKey: string; data: Record<string, unknown>; timestamp: number }>
> {
  try {
    const db = await getDB();
    return await db.getAll(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE);
  } catch (error) {
    logger.error(
      `Failed to get all supplier product data cache entries from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
    return [];
  }
}
 
/**
 * Empties the supplier product-data cache.
 * @category Utils
 * @returns Resolves once the store is empty.
 * @example
 * ```ts
 * await clearSupplierProductDataCache();
 * ```
 * @source
 */
export async function clearSupplierProductDataCache(): Promise<void> {
  try {
    const db = await getDB();
    await db.clear(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE);
  } catch (error) {
    logger.error(
      `Failed to clear supplier product data cache from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
  }
}
 
/* -------------------------------------------------------------------------- */
/*                          Supplier Stats                                    */
/* -------------------------------------------------------------------------- */
 
/**
 * Reads the per-supplier stats recorded for one day.
 * @category Utils
 * @param dateKey - The day to read, as `YYYY-MM-DD`.
 * @returns That day's stats keyed by supplier, or `undefined` when none exist.
 * @example
 * ```ts
 * const day = await getSupplierStatsEntry("2026-07-18");
 * day?.Loudwolf.queries; // => 3
 * ```
 * @source
 */
export async function getSupplierStatsEntry(
  dateKey: string,
): Promise<Record<string, SupplierDayStats> | undefined> {
  try {
    const db = await getDB();
    const record = await db.get(IDB_STORE.SUPPLIER_STATS, dateKey);
    return record?.suppliers;
  } catch (error) {
    logger.error(`Failed to get supplier stats entry from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return undefined;
  }
}
 
/**
 * Writes one day's per-supplier stats and notifies open surfaces by dispatching
 * {@link IDB_SUPPLIER_STATS_UPDATED}, so the stats panel re-reads without polling.
 * @category Utils
 * @param dateKey - The day being written, as `YYYY-MM-DD`.
 * @param suppliers - That day's stats keyed by supplier name.
 * @returns Resolves once the write completes.
 * @example
 * ```ts
 * await putSupplierStatsEntry("2026-07-18", { Loudwolf: { queries: 3, results: 41 } });
 * ```
 * @source
 */
export async function putSupplierStatsEntry(
  dateKey: string,
  suppliers: Record<string, SupplierDayStats>,
): Promise<void> {
  try {
    const db = await getDB();
    await db.put(IDB_STORE.SUPPLIER_STATS, { dateKey, suppliers });
    emitSupplierStatsUpdated();
  } catch (error) {
    logger.error(`Failed to put supplier stats entry in IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/**
 * Reads every day of supplier stats, flattened into a `dateKey -> suppliers` map.
 * @category Utils
 * @returns All recorded stats, or `{}` when none exist or the read fails.
 * @example
 * ```ts
 * const stats = await getAllSupplierStats();
 * stats["2026-07-18"].Loudwolf.queries; // => 3
 * ```
 * @source
 */
export async function getAllSupplierStats(): Promise<SupplierStatsData> {
  try {
    const db = await getDB();
    const all = await db.getAll(IDB_STORE.SUPPLIER_STATS);
    const result: SupplierStatsData = {};
    for (const record of all) {
      result[record.dateKey] = record.suppliers;
    }
    return result;
  } catch (error) {
    logger.error(`Failed to get all supplier stats from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return {};
  }
}
 
/**
 * Deletes specific days of supplier stats in one transaction, used to prune
 * days that have aged out of the retention window.
 * @category Utils
 * @param dateKeys - The days to delete, as `YYYY-MM-DD` strings.
 * @returns Resolves once every row is deleted.
 * @example
 * ```ts
 * await deleteSupplierStatsEntries(["2026-06-01", "2026-06-02"]);
 * ```
 * @source
 */
export async function deleteSupplierStatsEntries(dateKeys: string[]): Promise<void> {
  try {
    const db = await getDB();
    const tx = db.transaction(IDB_STORE.SUPPLIER_STATS, 'readwrite');
    for (const dateKey of dateKeys) {
      tx.store.delete(dateKey);
    }
    await tx.done;
  } catch (error) {
    logger.error(
      `Failed to delete supplier stats entries from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
  }
}
 
/**
 * Removes all recorded supplier stats.
 * @category Utils
 * @returns Resolves once the store is empty.
 * @example
 * ```ts
 * await clearSupplierStats();
 * ```
 * @source
 */
export async function clearSupplierStats(): Promise<void> {
  try {
    const db = await getDB();
    await db.clear(IDB_STORE.SUPPLIER_STATS);
  } catch (error) {
    logger.error(`Failed to clear supplier stats from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                          Excluded Products                                 */
/* -------------------------------------------------------------------------- */
 
/**
 * Load the user's excluded-products map from the `excludedProducts` object
 * store. The whole map lives under a single row keyed by `"current"` (same
 * single-row pattern used by `searchResults`), so this is a single read.
 * Returns `{}` when the store is empty or the read fails, letting callers
 * treat the result as always-valid without null-checking.
 * @category Utils
 * @returns Map of md5 exclusion key → entry, or `{}` when absent.
 * @example
 * ```ts
 * const excluded = await getExcludedProducts();
 * // => { "a1b2c3…": { url: "https://…", supplier: "Loudwolf",
 * //                   title: "Acetone 500ml", excludedAt: 1713301200000 } }
 * if (excluded[key]) {
 *   // product is on the ignore list
 * }
 * ```
 * @source
 */
export async function getExcludedProducts(): Promise<ExcludedProductsMap> {
  try {
    const db = await getDB();
    const record = await db.get(IDB_STORE.EXCLUDED_PRODUCTS, 'current');
    return record?.map ?? {};
  } catch (error) {
    logger.error(`Failed to get excluded products from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return {};
  }
}
 
/**
 * Write the full excluded-products map back into IndexedDB, overwriting the
 * previous value. Callers typically read via `getExcludedProducts`, mutate
 * the returned object, and pass it back here — the object store holds one
 * row keyed by `"current"` so each call is a complete replacement.
 * @category Utils
 * @param map - The map to persist. Pass `{}` to effectively clear.
 * @returns Resolves once the write completes; errors are logged, not thrown.
 * @example
 * ```ts
 * const map = await getExcludedProducts();
 * map["a1b2c3…"] = { url, supplier: "Loudwolf", title, excludedAt: Date.now() };
 * await putExcludedProducts(map);
 * ```
 * @source
 */
export async function putExcludedProducts(map: ExcludedProductsMap): Promise<void> {
  try {
    const db = await getDB();
    await db.put(IDB_STORE.EXCLUDED_PRODUCTS, { id: 'current', map });
  } catch (error) {
    logger.error(`Failed to put excluded products in IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/**
 * Remove the excluded-products row from IndexedDB entirely. After this, a
 * subsequent `getExcludedProducts()` returns `{}`. Used by the bulk
 * `clearAllCaches` flow; callers don't typically invoke this directly.
 * @category Utils
 * @returns Resolves once the delete completes; errors are logged, not thrown.
 * @example
 * ```ts
 * await clearExcludedProducts();
 * const excluded = await getExcludedProducts(); // => {}
 * ```
 * @source
 */
export async function clearExcludedProducts(): Promise<void> {
  try {
    const db = await getDB();
    await db.delete(IDB_STORE.EXCLUDED_PRODUCTS, 'current');
  } catch (error) {
    logger.error(`Failed to clear excluded products from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                              Price History                                 */
/* -------------------------------------------------------------------------- */
 
/**
 * Read a single price-history series by its id. The id is the product's
 * identity key for the base row, or `${productKey}::${variantKey}` for a
 * variant row. Returns `undefined` when no series exists yet (the first time a
 * product/variant is seen) or when the read fails.
 * @category Utils
 * @param id - The series id.
 * @returns The stored {@link PriceHistoryEntry}, or `undefined` when absent.
 * @example
 * ```ts
 * const series = await getPriceSeries("3f9c2a…");
 * const last = series?.points.at(-1)?.usd; // most recent USD price
 * ```
 * @source
 */
export async function getPriceSeries(id: string): Promise<PriceHistoryEntry | undefined> {
  try {
    const db = await getDB();
    return await db.get(IDB_STORE.PRICE_HISTORY, id);
  } catch (error) {
    logger.error(`Failed to get price series from IndexedDB: ${getErrorMessage(error)}`, { error });
    return undefined;
  }
}
 
/**
 * Write a price-history series, overwriting any existing row with the same id.
 * Callers read via {@link getPriceSeries}, append a point, then pass the whole
 * entry back — the store holds one row per series (keyed by `id`) so each call
 * is a complete replacement.
 * @category Utils
 * @param entry - The series to persist.
 * @returns Resolves once the write completes; errors are logged, not thrown.
 * @example
 * ```ts
 * await putPriceSeries({
 *   id: "3f9c2a…", productKey: "3f9c2a…", supplier: "Loudwolf",
 *   title: "Acetone 500ml", points: [{ t: Date.now(), usd: 19.99 }],
 *   updatedAt: Date.now(),
 * });
 * ```
 * @source
 */
export async function putPriceSeries(entry: PriceHistoryEntry): Promise<void> {
  try {
    const db = await getDB();
    await db.put(IDB_STORE.PRICE_HISTORY, entry);
  } catch (error) {
    logger.error(`Failed to put price series in IndexedDB: ${getErrorMessage(error)}`, { error });
  }
}
 
/**
 * Read every price-history series belonging to a product — its base row plus
 * one row per tracked variant — via the `productKey` index. Used by the detail
 * panel to render a product's full price history in one query. Returns `[]`
 * when the product has no recorded history or the read fails.
 * @category Utils
 * @param productKey - The product's identity key (shared by base and variants).
 * @returns All matching series (order unspecified), or `[]` when none.
 * @example
 * ```ts
 * const series = await getPriceSeriesByProduct("3f9c2a…");
 * // => [ base series, variant series, … ]
 * ```
 * @source
 */
export async function getPriceSeriesByProduct(productKey: string): Promise<PriceHistoryEntry[]> {
  try {
    const db = await getDB();
    return await db.getAllFromIndex(IDB_STORE.PRICE_HISTORY, 'productKey', productKey);
  } catch (error) {
    logger.error(
      `Failed to get price series by product from IndexedDB: ${getErrorMessage(error)}`,
      { error },
    );
    return [];
  }
}
 
/**
 * Read every stored price-history series (all base rows and variant rows across
 * every product). The app reads per-product via {@link getPriceSeriesByProduct};
 * this full-store read backs dev/debug tooling that needs the whole set.
 * @category Utils
 * @returns All price-history series, or `[]` when none / on error.
 * @example
 * ```ts
 * const all = await getAllPriceSeries();
 * all.length; // total number of tracked series
 * ```
 * @source
 */
export async function getAllPriceSeries(): Promise<PriceHistoryEntry[]> {
  try {
    const db = await getDB();
    return await db.getAll(IDB_STORE.PRICE_HISTORY);
  } catch (error) {
    logger.error(`Failed to get all price series from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return [];
  }
}
 
/**
 * Delete all price-history series. Exposed via the "Clear price history" button
 * in the settings panel. Deliberately kept out of {@link clearAllCaches} so a
 * routine cache clear never destroys the user's accumulated price history.
 * @category Utils
 * @returns Resolves once the store is cleared; errors are logged, not thrown.
 * @example
 * ```ts
 * await clearPriceHistory();
 * const series = await getPriceSeriesByProduct("3f9c2a…"); // => []
 * ```
 * @source
 */
export async function clearPriceHistory(): Promise<void> {
  try {
    const db = await getDB();
    await db.clear(IDB_STORE.PRICE_HISTORY);
  } catch (error) {
    logger.error(`Failed to clear price history from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                                App Meta                                    */
/* -------------------------------------------------------------------------- */
 
/**
 * Read the app version that last wrote or migrated the cache, from the single
 * `app_meta` row keyed `"current"`. Returns `undefined` on a fresh install (the
 * row has never been written) or when the read fails — callers treat `undefined`
 * as "no marker yet" and seed the current version instead of migrating.
 * @category Utils
 * @returns The stored semver string (e.g. `"1.0.0"`), or `undefined` when unset.
 * @example
 * ```ts
 * const from = await getStoredAppVersion(); // => "1.0.0" | undefined
 * ```
 * @source
 */
export async function getStoredAppVersion(): Promise<string | undefined> {
  try {
    const db = await getDB();
    const record = await db.get(IDB_STORE.APP_META, APP_META_KEY);
    return record?.appVersion;
  } catch (error) {
    logger.error(`Failed to get stored app version from IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
    return undefined;
  }
}
 
/**
 * Record the app version that now owns the cache, overwriting the single
 * `app_meta` row. Called after migrations complete, after a fresh-install seed,
 * and after a Cancel/reset, so the stored marker always reflects the version
 * whose data shape is currently in IndexedDB.
 * @category Utils
 * @param appVersion - The semver string to persist (typically `__APP_VERSION__`).
 * @returns Resolves once the write completes; errors are logged, not thrown.
 * @example
 * ```ts
 * await setStoredAppVersion("1.1.0");
 * await getStoredAppVersion(); // => "1.1.0"
 * ```
 * @source
 */
export async function setStoredAppVersion(appVersion: string): Promise<void> {
  try {
    const db = await getDB();
    await db.put(IDB_STORE.APP_META, {
      id: APP_META_KEY,
      appVersion,
      updatedAt: Date.now(),
    });
  } catch (error) {
    logger.error(`Failed to set stored app version in IndexedDB: ${getErrorMessage(error)}`, {
      error,
    });
  }
}
 
/**
 * Open the ChemPal database as an **untyped** `idb` handle for migration steps.
 * Unlike `getDB`, this returns `IDBPDatabase` without the schema generic, so
 * step code can read and write records in stores whose current-schema shape no
 * longer matches the data on disk (renamed stores, old record shapes) using plain
 * `string` store names — no type assertions required. The structural schema is
 * still owned by `getDB`'s `upgrade`; this connection never upgrades.
 * @category Utils
 * @returns A fresh untyped connection to the same `chempal` database.
 * @example
 * ```ts
 * const db = await getMigrationDb();
 * const rows = await db.getAll("supplier_query_cache");
 * ```
 * @source
 */
export async function getMigrationDb(): Promise<IDBPDatabase> {
  return openDB(DB_NAME, DB_VERSION);
}
 
/* -------------------------------------------------------------------------- */
/*                              Result Exports                                 */
/* -------------------------------------------------------------------------- */
 
/**
 * Stores a generated `.xlsx` export, then evicts the oldest exports until the
 * store is within **both** caps: at most `storage.maxExportEntries` records and at most
 * `storage.maxExportsCacheBytes` total bytes. The most recent export is always kept, even
 * if it alone exceeds the byte budget.
 * @category Utils
 * @param record - The export record to persist (its `id` is the store key).
 * @returns Resolves once the write and any eviction complete.
 * @example
 * ```ts
 * await putExport({
 *   id: crypto.randomUUID(), createdAt: Date.now(), filename: "chempal-export.xlsx",
 *   query: "acetone", scope: "filtered", rowCount: 12, sizeBytes: blob.size, blob,
 * });
 * ```
 * @source
 */
export async function putExport(record: ExportRecord): Promise<void> {
  try {
    const db = await getDB();
    const tx = db.transaction(IDB_STORE.EXPORTS, 'readwrite');
    const store = tx.objectStore(IDB_STORE.EXPORTS);
    await store.put(record);
 
    // Oldest first, so we can evict from the front while keeping the newest.
    const all = (await store.getAll()).sort((a, b) => a.createdAt - b.createdAt);
    let totalBytes = all.reduce((sum, entry) => sum + entry.sizeBytes, 0);
    let index = 0;
    while (
      index < all.length - 1 &&
      (all.length - index > MAX_EXPORT_ENTRIES || totalBytes > MAX_EXPORT_CACHE_BYTES)
    ) {
      const victim = all[index];
      await store.delete(victim.id);
      totalBytes -= victim.sizeBytes;
      index++;
    }
 
    await tx.done;
    emitExportsUpdated();
  } catch (error) {
    logger.error(`Failed to put export in IndexedDB: ${getErrorMessage(error)}`, { error });
  }
}
 
/**
 * Reads every cached export, newest first, for the export-history list.
 * @category Utils
 * @returns All stored export records ordered by `createdAt` descending, or `[]` on failure.
 * @example
 * ```ts
 * const exports = await getAllExports();
 * exports[0].filename; // => most recent export's filename
 * ```
 * @source
 */
export async function getAllExports(): Promise<ExportRecord[]> {
  try {
    const db = await getDB();
    const all = await db.getAll(IDB_STORE.EXPORTS);
    return all.sort((a, b) => b.createdAt - a.createdAt);
  } catch (error) {
    logger.error(`Failed to get exports from IndexedDB: ${getErrorMessage(error)}`, { error });
    return [];
  }
}
 
/**
 * Deletes a single cached export by id.
 * @category Utils
 * @param id - The export record's id.
 * @returns Resolves once the delete completes.
 * @example
 * ```ts
 * await deleteExport(record.id);
 * ```
 * @source
 */
export async function deleteExport(id: string): Promise<void> {
  try {
    const db = await getDB();
    await db.delete(IDB_STORE.EXPORTS, id);
    emitExportsUpdated();
  } catch (error) {
    logger.error(`Failed to delete export from IndexedDB: ${getErrorMessage(error)}`, { error });
  }
}
 
/**
 * Empties the export cache.
 * @category Utils
 * @returns Resolves once the store is empty.
 * @example
 * ```ts
 * await clearExports();
 * ```
 * @source
 */
export async function clearExports(): Promise<void> {
  try {
    const db = await getDB();
    await db.clear(IDB_STORE.EXPORTS);
    emitExportsUpdated();
  } catch (error) {
    logger.error(`Failed to clear exports from IndexedDB: ${getErrorMessage(error)}`, { error });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                              Storage stats                                 */
/* -------------------------------------------------------------------------- */
 
/**
 * Per-store record count + serialized JSON size, plus the summed total.
 * @category Utils
 */
export interface IdbStorageBreakdown {
  byStore: Record<IdbStore, { count: number; bytes: number }>;
  totalBytes: number;
}
 
/**
 * Measure every IndexedDB object store: the number of records it holds and the
 * byte size of its contents when serialized to JSON. Used by the settings panel
 * to show cache/price-history sizes; the summed `totalBytes` can be paired with
 * `navigator.storage.estimate()` to scale each store's JSON size up to its true
 * on-disk footprint (indexes, keys, structured-clone overhead). Returns all-zero
 * counts on failure.
 * @category Utils
 * @returns A per-store breakdown of record counts and JSON byte sizes, plus the total.
 * @example
 * ```ts
 * const { byStore, totalBytes } = await getIdbStorageBreakdown();
 * byStore["price_history"].count; // => number of price series
 * totalBytes;                     // => summed JSON bytes across all stores
 * ```
 * @source
 */
export async function getIdbStorageBreakdown(): Promise<IdbStorageBreakdown> {
  const byStore: Record<IdbStore, { count: number; bytes: number }> = {
    [IDB_STORE.SEARCH_RESULTS]: { count: 0, bytes: 0 },
    [IDB_STORE.SEARCH_HISTORY]: { count: 0, bytes: 0 },
    [IDB_STORE.SUPPLIER_QUERY_CACHE]: { count: 0, bytes: 0 },
    [IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE]: { count: 0, bytes: 0 },
    [IDB_STORE.SUPPLIER_STATS]: { count: 0, bytes: 0 },
    [IDB_STORE.EXCLUDED_PRODUCTS]: { count: 0, bytes: 0 },
    [IDB_STORE.PRICE_HISTORY]: { count: 0, bytes: 0 },
    [IDB_STORE.APP_META]: { count: 0, bytes: 0 },
    [IDB_STORE.EXPORTS]: { count: 0, bytes: 0 },
    [IDB_STORE.CHEMICAL_DB]: { count: 0, bytes: 0 },
  };
  try {
    const db = await getDB();
    for (const store of Object.values(IDB_STORE)) {
      const entries = await db.getAll(store);
      // Export records hold Blobs, which JSON.stringify flattens to `{}`; sum the
      // tracked `sizeBytes` instead so the breakdown reflects real on-disk size.
      const bytes =
        store === IDB_STORE.EXPORTS
          ? entries.reduce(
              (sum, entry) =>
                sum +
                (typeof entry === 'object' &&
                entry !== null &&
                'sizeBytes' in entry &&
                typeof entry.sizeBytes === 'number'
                  ? entry.sizeBytes
                  : 0),
              0,
            )
          : new Blob([JSON.stringify(entries)]).size;
      byStore[store] = { count: entries.length, bytes };
    }
  } catch (error) {
    logger.error(`Failed to compute IndexedDB storage breakdown: ${getErrorMessage(error)}`, {
      error,
    });
  }
  const totalBytes = Object.values(byStore).reduce((sum, entry) => sum + entry.bytes, 0);
  return { byStore, totalBytes };
}
 
/* -------------------------------------------------------------------------- */
/*                                 Bulk                                       */
/* -------------------------------------------------------------------------- */
 
/**
 * Clears every cache-bearing store in one transaction: search results, history,
 * both supplier caches, stats, and excluded products. Backs the "clear cache"
 * action in settings.
 * @category Utils
 * @returns Resolves once all stores are empty.
 * @example
 * ```ts
 * await clearAllCaches();
 * ```
 * @source
 */
export async function clearAllCaches(): Promise<void> {
  try {
    const db = await getDB();
    const tx = db.transaction(
      [
        IDB_STORE.SEARCH_RESULTS,
        IDB_STORE.SEARCH_HISTORY,
        IDB_STORE.SUPPLIER_QUERY_CACHE,
        IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE,
        IDB_STORE.SUPPLIER_STATS,
        IDB_STORE.EXCLUDED_PRODUCTS,
        IDB_STORE.CHEMICAL_DB,
      ],
      'readwrite',
    );
    await Promise.all([
      tx.objectStore(IDB_STORE.SEARCH_RESULTS).clear(),
      tx.objectStore(IDB_STORE.SEARCH_HISTORY).clear(),
      tx.objectStore(IDB_STORE.SUPPLIER_QUERY_CACHE).clear(),
      tx.objectStore(IDB_STORE.SUPPLIER_PRODUCT_DATA_CACHE).clear(),
      tx.objectStore(IDB_STORE.SUPPLIER_STATS).clear(),
      tx.objectStore(IDB_STORE.EXCLUDED_PRODUCTS).clear(),
      tx.objectStore(IDB_STORE.CHEMICAL_DB).clear(),
      tx.done,
    ]);
    emitSearchResultsCleared();
  } catch (error) {
    logger.error(`Failed to clear all IndexedDB caches: ${getErrorMessage(error)}`, { error });
  }
}
 
/* -------------------------------------------------------------------------- */
/*                              Chemical reference DB                         */
/* -------------------------------------------------------------------------- */
 
/**
 * Reads the cached OSHA OBIS chemical dataset from the single `chemical_db` row.
 * @category Utils
 * @returns The stored record, or `undefined` when nothing is cached or the read fails.
 * @example
 * ```ts
 * const record = await getChemicalDb();
 * record?.chemicals.length; // => 835
 * ```
 * @source
 */
export async function getChemicalDb(): Promise<ChemicalDbRecord | undefined> {
  try {
    const db = await getDB();
    return await db.get(IDB_STORE.CHEMICAL_DB, CHEMICAL_DB_KEY);
  } catch (error) {
    logger.error(`Failed to read chemical DB from IndexedDB: ${getErrorMessage(error)}`, { error });
    return undefined;
  }
}
 
/**
 * Replaces the cached OSHA OBIS chemical dataset.
 * @category Utils
 * @param chemicals - The slimmed chemical records to store.
 * @param fetchedAt - Epoch milliseconds the dataset was downloaded; drives TTL expiry.
 * @returns Resolves once the write completes; errors are logged, not thrown.
 * @example
 * ```ts
 * await putChemicalDb(records, Date.now());
 * ```
 * @source
 */
export async function putChemicalDb(chemicals: OshaChemical[], fetchedAt: number): Promise<void> {
  try {
    const db = await getDB();
    await db.put(IDB_STORE.CHEMICAL_DB, { id: CHEMICAL_DB_KEY, fetchedAt, chemicals });
  } catch (error) {
    logger.error(`Failed to write chemical DB to IndexedDB: ${getErrorMessage(error)}`, { error });
  }
}