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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
const mongoose = require('mongoose');
const axios = require('axios');
const xlsx = require('xlsx');
const FormData = require('form-data');
const { cloudinary } = require('../config/cloudinary');
const Product = require('../models/productModel');
const Category = require('../models/categoryModel');
const Provider = require('../models/providerModel');
const Brand = require('../models/brandModel');
const User = require('../models/userModel');
const APIFeatures = require('../utils/apiFeatures');
const {
  createSmartSearchRegex,
  convertArabicNumerals,
} = require('../utils/arabicSearch');
const {
  notifyPastBuyersProductBackInStock,
  notifyStockSubscribers,
} = require('../utils/notificationService');
const {
  extractVoiceEntities,
  buildVoiceFilterQuery,
  buildMongoVoiceQuery,
  scoreProduct: scoreVoiceProduct,
  buildSearchTextFromEntities,
} = require('../utils/voiceSearch');

// Paste your Cloudinary logo URL here to force it as import fallback cover.
// Example: https://res.cloudinary.com/<cloud-name>/image/upload/v1234567890/samoulla/system/logo-cover.png
const HARDCODED_IMPORT_LOGO_COVER =
  'https://res.cloudinary.com/dm9ym99zh/image/upload/v1771470584/Asset_16_wfto7q.png';

const IMPORT_FALLBACK_COVER_IMAGE =
  HARDCODED_IMPORT_LOGO_COVER ||
  process.env.IMPORT_FALLBACK_COVER_IMAGE ||
  'https://placehold.co/1000x1000/png?text=No+Image';

const isImageUrlReachable = async (url) => {
  if (!url || typeof url !== 'string' || !url.startsWith('http')) return false;

  try {
    const response = await axios.head(url, {
      timeout: 7000,
      maxRedirects: 5,
      validateStatus: () => true,
    });

    if (response.status === 405) {
      const fallbackResponse = await axios.get(url, {
        timeout: 7000,
        maxRedirects: 5,
        headers: { Range: 'bytes=0-0' },
        validateStatus: () => true,
      });
      return fallbackResponse.status >= 200 && fallbackResponse.status < 400;
    }

    return response.status >= 200 && response.status < 400;
  } catch (_) {
    return false;
  }
};

// Helper to auto-upload external image URLs to Cloudinary during import
const uploadExternalImage = async (url, productId, isCover = true) => {
  if (!url || typeof url !== 'string') return '';

  // Skip non-URL values
  if (!url.startsWith('http')) return '';

  // Reuse URL only if it's already hosted on the current Cloudinary cloud.
  // Legacy Cloudinary URLs (e.g., old project cloud) are re-hosted to avoid 404s.
  const currentCloudName = process.env.CLOUDINARY_CLOUD_NAME;
  let sourceCloudName = null;

  try {
    const parsed = new URL(url);
    const match = parsed.hostname.match(/^res\.cloudinary\.com$/i)
      ? parsed.pathname.match(/^\/([^/]+)\//)
      : null;
    sourceCloudName = match ? match[1] : null;

    const inTargetFolderRegex = new RegExp(
      `/samoulla/products/${String(productId).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/`,
    );
    const isAlreadyInTargetFolder = inTargetFolderRegex.test(parsed.pathname);

    if (sourceCloudName && sourceCloudName === currentCloudName) {
      const reachable = await isImageUrlReachable(url);
      if (!reachable) return '';

      // Keep existing URL only when it's already inside the product _id folder.
      // Otherwise, re-host to enforce folder consistency for this product.
      if (isAlreadyInTargetFolder) return url;
    }
  } catch (_) {
    return '';
  }

  try {
    const prefix = isCover ? 'cover' : 'img';
    const result = await cloudinary.uploader.upload(url, {
      folder: `samoulla/products/${productId}`,
      public_id: `${prefix}-${Date.now()}`,
      transformation: [
        { width: 1000, height: 1000, crop: 'limit' },
        { quality: 'auto' },
        { fetch_format: 'auto' },
      ],
    });
    return result.secure_url;
  } catch (err) {
    console.error(`Auto-upload failed for ${url}:`, err.message);
    return '';
  }
};

// Helper to delete a single image from Cloudinary by its secure URL
const deleteCloudinaryImage = async (url) => {
  if (!url || typeof url !== 'string' || !url.includes('cloudinary.com'))
    return;
  const currentCloudName = cloudinary.config().cloud_name;
  if (!url.includes(`/${currentCloudName}/`)) return; // Not our cloud, don't touch it
  try {
    // Extract public_id: everything after /upload/(v<digits>/) and before the file extension
    const match = url.match(/\/upload\/(?:v\d+\/)?(.+?)(?:\.[a-z0-9]+)?$/i);
    if (!match) return;
    const publicId = match[1];
    await cloudinary.uploader.destroy(publicId);
  } catch (err) {
    console.error(`Failed to delete Cloudinary image ${url}:`, err.message);
  }
};

// Helper to notify the AI service to reload its product cache
const triggerAiReload = async () => {
  try {
    const aiUrl = process.env.AI_SERVICE_URL || 'http://localhost:9001';
    await axios.post(`${aiUrl}/api/reload-products`);
    console.log('AI product cache reload triggered successfully');
  } catch (err) {
    // Fail silently in production, just log it
    console.error('Failed to trigger AI product reload:', err.message);
  }
};

// Get all products
exports.getAllProducts = async (req, res) => {
  try {
    // 1) Filter by Category (Hierarchy-aware)
    if (req.query.category !== undefined) {
      if (
        req.query.category === 'جميع المنتجات' ||
        req.query.category === '' ||
        req.query.category === 'all'
      ) {
        delete req.query.category;
      } else {
        const categoryValues = req.query.category.split(',');
        const objectIds = [];
        const numericIds = [];
        const nameValues = [];

        categoryValues.forEach((val) => {
          if (mongoose.Types.ObjectId.isValid(val)) objectIds.push(val);
          else if (/^\d+$/.test(val)) numericIds.push(val);
          else nameValues.push(val);
        });

        // Find initial categories in bulk
        const foundCategories = await Category.find({
          $or: [
            { _id: { $in: objectIds } },
            { id: { $in: numericIds } },
            { nameAr: { $in: nameValues } },
            { nameEn: { $in: nameValues } },
          ],
        });

        const categoryIds = foundCategories.map((c) => c._id);

        if (categoryIds.length > 0) {
          // Get descendants (Level 1)
          const subCategories = await Category.find({
            parent: { $in: categoryIds },
          });
          const subIds = subCategories.map((c) => c._id);
          categoryIds.push(...subIds);

          if (subIds.length > 0) {
            // Level 2 descendants
            const subSubCategories = await Category.find({
              parent: { $in: subIds },
            });
            categoryIds.push(...subSubCategories.map((c) => c._id));
          }
        }

        if (categoryIds.length > 0) {
          req.query.category = { $in: [...new Set(categoryIds)] };
        } else {
          req.query.category = { $in: [new mongoose.Types.ObjectId()] };
        }
      }
    }

    // 2) Filter by Brand (if provided)
    if (req.query.brand) {
      const brandValues = req.query.brand.split(',');
      const isObjectId = mongoose.Types.ObjectId.isValid(brandValues[0]);
      const isNumericId = /^\d+$/.test(brandValues[0]);

      if (isObjectId) {
        req.query.brand = { $in: brandValues };
      } else if (isNumericId) {
        // Find brand object by numeric ID
        const brands = await Brand.find({ id: { $in: brandValues } });
        if (brands.length > 0) {
          // If product stores name, use names. If it stores ID, use IDs.
          // For now, let's support both or prioritize names since the current model uses strings.
          req.query.brand = { $in: brands.map((b) => b.nameEn) };
        } else {
          req.query.brand = { $in: ['Unknown Brand'] };
        }
      } else {
        // It's a name
        req.query.brand = { $in: brandValues };
      }
    }

    // 3) Filter by Provider (if provided) - Supports multiple providers by name or slug
    if (req.query.provider) {
      const providerValues = req.query.provider.split(',');
      const providers = await Provider.find({
        $or: [
          { storeName: { $in: providerValues } },
          { slug: { $in: providerValues } },
          {
            _id: {
              $in: providerValues.filter((id) =>
                mongoose.Types.ObjectId.isValid(id),
              ),
            },
          },
        ],
      });

      if (providers.length > 0) {
        req.query.provider = { $in: providers.map((p) => p._id) };
      } else {
        req.query.provider = { $in: ['000000000000000000000000'] };
      }
    }

    // 3) Filter by Sale Price (if onSale is true)
    let salePriceQuery = {};
    if (req.query.onSale === 'true') {
      salePriceQuery = { salePrice: { $gt: 0 } };
      delete req.query.onSale;
    }

    // Store original search term for relevance scoring (before it gets deleted)
    const originalSearchTerm = req.query.search
      ? convertArabicNumerals(req.query.search.trim())
      : null;
    const hasExplicitSort = !!req.query.sort;

    // 4) Search by Name, Description, Barcode, or ID (if provided)
    let searchQuery = {};
    let relatedQuery = null; // $or query for "related" products (any-word match)
    if (req.query.search) {
      // TRACK SEARCH: Save the user's last 5 search terms in their profile if logged in
      if (req.user) {
        const searchTerm = req.query.search.trim();
        if (searchTerm) {
          // Remove if already exists to move it to the end (most recent)
          const searchHistory = (req.user.recentSearches || []).filter(
            (s) => s.toLowerCase() !== searchTerm.toLowerCase(),
          );
          searchHistory.push(searchTerm);

          // Keep only last 5
          if (searchHistory.length > 5) {
            searchHistory.shift();
          }

          req.user.recentSearches = searchHistory;
          // Non-blocking update
          User.findByIdAndUpdate(req.user._id, {
            recentSearches: searchHistory,
          }).catch(() => {});
        }
      }

      const searchTerms = req.query.search
        .split(' ')
        .map((term) => convertArabicNumerals(term.trim()))
        .filter((term) => term.length > 0);

      if (searchTerms.length > 0) {
        // Pre-fetch all matching categories for all terms at once
        const allSearchRegexes = searchTerms.map((term) =>
          createSmartSearchRegex(term),
        );
        const allMatchingCategories = await Category.find({
          $or: allSearchRegexes.flatMap((regex) => [
            { nameAr: regex },
            { nameEn: regex },
          ]),
        }).select('_id nameAr nameEn');

        const searchConditions = searchTerms.map((term) => {
          const searchRegex = createSmartSearchRegex(term);

          const matchingCategoryIds = allMatchingCategories
            .filter(
              (cat) =>
                (cat.nameAr && cat.nameAr.match(searchRegex)) ||
                (cat.nameEn && cat.nameEn.match(searchRegex)),
            )
            .map((cat) => cat._id);

          // Build search conditions array
          const conditions = [
            { nameAr: searchRegex },
            { nameEn: searchRegex },
            { descriptionAr: searchRegex },
            { descriptionEn: searchRegex },
            { barCode: searchRegex },
          ];

          if (matchingCategoryIds && matchingCategoryIds.length > 0) {
            conditions.push({ category: { $in: matchingCategoryIds } });
          }

          // Check if term looks like a hex string (potential partial ObjectId)
          if (/^[0-9a-fA-F]+$/.test(term)) {
            conditions.push({
              $expr: {
                $regexMatch: {
                  input: { $toString: '$_id' },
                  regex: term,
                  options: 'i',
                },
              },
            });
          }

          return { $or: conditions };
        });

        searchQuery = { $and: searchConditions };

        // Also build an $or query for "related" results (match ANY word).
        // When multiple words are searched, this lets us append products that
        // match some — but not all — of the words after the primary matches.
        if (searchTerms.length > 1) {
          // Flatten each per-word condition into one big $or
          const relatedOrConditions = searchConditions.flatMap(
            (c) => c.$or || [],
          );
          relatedQuery = { $or: relatedOrConditions, ...salePriceQuery };
        }
      }

      // Remove search from query so it doesn't interfere with APIFeatures
      delete req.query.search;
    }

    // Combine search and salePrice queries
    const combinedQuery = { ...searchQuery, ...salePriceQuery };

    // Calculate pagination params up front
    const page = req.query.page * 1 || 1;
    const limit = req.query.limit * 1 || 100;

    // When search is active and no explicit sort, fetch ALL matches so we can
    // score every result for relevance before paginating. This ensures the best
    // match is always on page 1 regardless of insertion order in the DB.
    let products;
    let totalCount;

    if (originalSearchTerm && !hasExplicitSort) {
      // Fetch ALL primary matching products ($and — all words must match)
      const allFeaturesQuery = new APIFeatures(
        Product.find(combinedQuery)
          .populate('category', 'nameAr _id')
          .populate('provider', 'storeName _id'),
        req.query,
      )
        .filter()
        .sort()
        .limitFields();

      const primaryProducts = await allFeaturesQuery.query.lean();
      const primaryIds = new Set(primaryProducts.map((p) => String(p._id)));

      // Fetch related products ($or — match ANY word) that aren't already in primary set
      let relatedProducts = [];
      if (relatedQuery) {
        relatedProducts = await Product.find({
          ...relatedQuery,
          _id: { $nin: [...primaryIds] }, // exclude already-found primary products
        })
          .populate('category', 'nameAr _id')
          .populate('provider', 'storeName _id')
          .select('-__v')
          .lean();
      }

      // Merge: primary first, related appended
      // Scoring below will rank primary products higher (they match all words)
      products = [...primaryProducts, ...relatedProducts];
      totalCount = products.length;
    } else {
      // Regular path: paginate in DB (faster when no search or explicit sort)
      const countFeatures = new APIFeatures(
        Product.find(combinedQuery)
          .populate('category', 'nameAr _id')
          .populate('provider', 'storeName _id'),
        req.query,
      )
        .filter()
        .sort()
        .limitFields();

      totalCount = await Product.countDocuments(
        countFeatures.query.getFilter(),
      );

      const features = new APIFeatures(
        Product.find(combinedQuery)
          .populate('category', 'nameAr _id')
          .populate('provider', 'storeName _id'),
        req.query,
      )
        .filter()
        .sort()
        .limitFields()
        .paginate();

      products = await features.query.lean();
    }

    // Apply intelligent relevance scoring if search is active and no explicit sort
    if (originalSearchTerm && !hasExplicitSort && products.length > 0) {
      // Normalize for Arabic-aware comparisons
      const { normalizeArabic } = require('../utils/arabicSearch');
      const normalizedSearchTerm = normalizeArabic(originalSearchTerm);
      const searchWords = normalizedSearchTerm
        .split(/\s+/)
        .filter((w) => w.length > 0);
      const isMultiWord = searchWords.length > 1;

      /**
       * Score a single string field against the search term.
       * Returns a score 0-100 for that field.
       */
      const IS_PURE_NUMBER = /^\d+(\.\d+)?$/;
      const scoreField = (rawText) => {
        if (!rawText) return 0;
        const norm = normalizeArabic(rawText);

        // --- Full-phrase matching ---
        // Exact full match (always valid)
        if (norm === normalizedSearchTerm) return 100;

        // For pure-number queries (e.g. "5"), don't use startsWith/includes
        // because "5" would falsely match "1500", "50", etc.
        if (!IS_PURE_NUMBER.test(normalizedSearchTerm)) {
          // Starts with full phrase
          if (norm.startsWith(normalizedSearchTerm)) return 85;
          // Contains the full phrase as a substring
          if (norm.includes(normalizedSearchTerm)) return 65;
        }

        if (isMultiWord) {
          // For multi-word queries: score based on how many words match in the name.
          // Numbers must match as exact whole words (so "5" does NOT match "1500").
          const IS_NUMBER = /^\d+(\.\d+)?$/;
          let wordMatchCount = 0;
          let allWordsMatched = true;
          const normWords = norm.split(/\s+/);

          for (const word of searchWords) {
            let matched = false;
            if (IS_NUMBER.test(word)) {
              // Numeric token: require exact equality only
              matched = normWords.some((nw) => nw === word);
            } else {
              // Text token: allow starts-with / contains (fuzzy)
              matched = normWords.some(
                (nw) => nw === word || nw.startsWith(word) || nw.includes(word),
              );
            }
            if (matched) {
              wordMatchCount++;
            } else {
              allWordsMatched = false;
            }
          }

          if (wordMatchCount === 0) return 0;
          const ratio = wordMatchCount / searchWords.length;
          // All words matched → high score
          if (ratio === 1) return allWordsMatched ? 80 : 72;
          // Partial match: scale 10-58
          return 10 + Math.round(ratio * 48);
        }

        // Single-word fallback
        // Whole-word boundary match
        try {
          const wbRegex = new RegExp(
            `(^|\\s)${normalizedSearchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s|$)`,
          );
          if (wbRegex.test(norm)) return 60;
        } catch (_) {
          // ignore regex errors
        }

        return 0;
      };

      /**
       * Combined scorer for a product.
       * Name scores are weighted heavily; description/category as fallback.
       */
      const scoreProduct = (product) => {
        const nameArScore = scoreField(product.nameAr);
        const nameEnScore = scoreField(product.nameEn);
        const nameScore = Math.max(nameArScore, nameEnScore);

        // If we got a solid name match, return it directly
        if (nameScore >= 60) return nameScore;

        // Check description
        const descArText = Array.isArray(product.descriptionAr)
          ? product.descriptionAr.join(' ')
          : product.descriptionAr || '';
        const descEnText = Array.isArray(product.descriptionEn)
          ? product.descriptionEn.join(' ')
          : product.descriptionEn || '';
        const descScore = Math.max(
          scoreField(descArText),
          scoreField(descEnText),
        );

        if (descScore > 0)
          return Math.max(nameScore, Math.round(descScore * 0.4));

        // Matched via category/barcode — keep it low but above 0
        return nameScore > 0 ? nameScore : 8;
      };

      // Sort products by score (descending)
      products = products.sort((a, b) => scoreProduct(b) - scoreProduct(a));

      // Apply manual pagination after scoring (only for search path)
      if (originalSearchTerm && !hasExplicitSort) {
        const skip = (page - 1) * limit;
        products = products.slice(skip, skip + limit);
      }
    }

    const totalPages = Math.ceil(totalCount / limit);

    res.status(200).json({
      status: 'success',
      results: products.length,
      totalCount,
      totalPages,
      currentPage: page,
      data: {
        products,
      },
    });
  } catch (err) {
    console.error('getAllProducts error:', err);
    res.status(500).json({
      status: 'fail',
      message: 'Error fetching products',
      error: err.message,
    });
  }
};

// Get search suggestions
exports.getSuggestions = async (req, res) => {
  try {
    const { search } = req.query;
    if (!search) {
      return res
        .status(200)
        .json({ status: 'success', data: { products: [], categories: [] } });
    }

    const {
      createSmartSearchRegex,
      getSimilarity,
      convertArabicNumerals,
    } = require('../utils/arabicSearch');

    const searchTerms = search
      .split(' ')
      .map((term) => convertArabicNumerals(term.trim()))
      .filter((term) => term.length > 0);
    let productQuery = {};
    let categoryQuery = {};

    if (searchTerms.length > 0) {
      const searchConditions = searchTerms.map((term) => {
        const searchRegex = createSmartSearchRegex(term);
        return {
          $or: [{ nameAr: searchRegex }, { nameEn: searchRegex }],
        };
      });

      productQuery = { $and: searchConditions };
      categoryQuery = { $and: searchConditions };
    }

    // Fetch matching products (fetch more for ranking)
    let products = await Product.find(productQuery)
      .select('nameAr nameEn imageCover price slug _id')
      .limit(100)
      .lean();

    // Rank products by similarity
    products = products
      .map((p) => ({
        ...p,
        score: Math.max(
          getSimilarity(search, p.nameAr),
          getSimilarity(search, p.nameEn),
        ),
      }))
      .sort((a, b) => b.score - a.score)
      .slice(0, 5);

    // Fetch matching categories
    let categories = await Category.find(categoryQuery)
      .select('nameAr nameEn _id id')
      .limit(50)
      .lean();

    // Rank categories by similarity
    categories = categories
      .map((c) => ({
        ...c,
        score: Math.max(
          getSimilarity(search, c.nameAr),
          getSimilarity(search, c.nameEn),
        ),
      }))
      .sort((a, b) => b.score - a.score)
      .slice(0, 3);

    res.status(200).json({
      status: 'success',
      data: {
        products,
        categories,
      },
    });
  } catch (err) {
    res.status(500).json({
      status: 'fail',
      message: 'Error fetching suggestions',
    });
  }
};

// Voice-based technical search (transcript -> entities -> filters -> ranking)
exports.voiceSearch = async (req, res) => {
  try {
    const { transcript = '', limit = 12 } = req.body || {};

    if (!transcript || !String(transcript).trim()) {
      return res.status(400).json({
        status: 'fail',
        message: 'transcript is required',
      });
    }

    const cappedLimit = Math.min(Math.max(Number(limit) || 12, 1), 40);

    const categories = await Category.find({})
      .select('_id id nameAr nameEn')
      .lean();

    const extraction = extractVoiceEntities({
      transcript: String(transcript),
      categories,
    });

    const { entities } = extraction;

    const queryEntities = {
      categoryId: entities.category?.id || null,
      categoryObjectId: entities.category?.objectId || null,
      powerType: entities.powerType,
      voltage: entities.voltage,
      powerWatts: entities.powerWatts,
      sizeMm: entities.sizeMm,
      usage: entities.usage,
      minPrice: entities.minPrice,
      maxPrice: entities.maxPrice,
      keywords: Array.isArray(entities.keywords) ? entities.keywords : [],
    };

    const mongoQuery = buildMongoVoiceQuery(queryEntities);
    let candidates = await Product.find(mongoQuery)
      .populate('category', 'nameAr nameEn _id id')
      .populate('provider', 'storeName _id')
      .limit(cappedLimit * 5)
      .lean();

    // Strong fallback: if no direct results, search broad set with optional price filter.
    if (candidates.length === 0) {
      const fallbackQuery = {};

      if (queryEntities.minPrice !== null || queryEntities.maxPrice !== null) {
        fallbackQuery.price = {};
        if (queryEntities.minPrice !== null) {
          fallbackQuery.price.$gte = queryEntities.minPrice;
        }
        if (queryEntities.maxPrice !== null) {
          fallbackQuery.price.$lte = queryEntities.maxPrice;
        }
      }

      candidates = await Product.find(fallbackQuery)
        .populate('category', 'nameAr nameEn _id id')
        .populate('provider', 'storeName _id')
        .sort('-createdAt')
        .limit(cappedLimit * 10)
        .lean();
    }

    const rankedProducts = candidates
      .map((product) => ({
        ...product,
        relevanceScore: scoreVoiceProduct(product, queryEntities),
      }))
      .sort((a, b) => b.relevanceScore - a.relevanceScore)
      .slice(0, cappedLimit);

    const cleanedSearchText =
      buildSearchTextFromEntities(queryEntities) || transcript;
    const finalSearchText =
      cleanedSearchText.trim().length > 0 ? cleanedSearchText : transcript;

    const queryParams = {
      ...buildVoiceFilterQuery(queryEntities),
      search: finalSearchText,
    };

    return res.status(200).json({
      status: 'success',
      results: rankedProducts.length,
      data: {
        transcript,
        intent: extraction.intent,
        entities,
        queryParams,
        mongoQuery,
        candidatesFound: candidates.length,
        products: rankedProducts,
      },
    });
  } catch (err) {
    console.error('Voice search error:', err.message);
    return res.status(500).json({
      status: 'fail',
      message: 'Error processing voice search',
    });
  }
};

exports.transcribeVoice = async (req, res) => {
  try {
    if (!process.env.OPENAI_API_KEY) {
      return res.status(500).json({
        status: 'fail',
        message: 'OPENAI_API_KEY is not configured on the backend',
      });
    }

    if (!req.file || !req.file.buffer) {
      return res.status(400).json({
        status: 'fail',
        message: 'audio file is required',
      });
    }

    const formData = new FormData();
    const contentType = req.file.mimetype || 'audio/webm';
    formData.append('file', req.file.buffer, {
      filename: req.file.originalname || 'voice.webm',
      contentType,
    });
    formData.append('model', process.env.OPENAI_WHISPER_MODEL || 'whisper-1');

    const language = req.body?.language;
    if (language) {
      formData.append('language', String(language).slice(0, 5));
    }

    const whisperResponse = await axios.post(
      'https://api.openai.com/v1/audio/transcriptions',
      formData,
      {
        headers: {
          Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
          ...formData.getHeaders(),
        },
        maxBodyLength: Infinity,
        timeout: 30000,
      },
    );

    const transcript = whisperResponse?.data?.text?.trim() || '';

    return res.status(200).json({
      status: 'success',
      data: {
        transcript,
      },
    });
  } catch (error) {
    return res.status(500).json({
      status: 'fail',
      message: 'Failed to transcribe voice using Whisper API',
      error:
        error?.response?.data?.error?.message ||
        error.message ||
        'Unknown error',
    });
  }
};

// Get a single product by ID
exports.getProduct = async (req, res) => {
  try {
    const { id } = req.params;

    // Check if the provided ID is a valid MongoDB ObjectId
    const isObjectId = mongoose.Types.ObjectId.isValid(id);

    let product;
    if (isObjectId) {
      product = await Product.findById(id)
        .populate('category', 'nameAr nameEn _id id')
        .populate('provider', 'storeName name logo _id')
        .populate('reviews')
        .lean();
    } else {
      // If not an ObjectId, assume it's a slug
      product = await Product.findOne({ slug: id })
        .populate('category', 'nameAr nameEn _id id')
        .populate('provider', 'storeName name logo _id')
        .populate('reviews')
        .lean();
    }

    if (!product) {
      return res.status(404).json({
        status: 'fail',
        message: 'No product found with that ID or slug',
      });
    }

    res.status(200).json({
      status: 'success',
      data: {
        product,
      },
    });
  } catch (err) {
    res.status(500).json({
      status: 'fail',
      message: err.message,
    });
  }
};

// Create a new product
exports.createProduct = async (req, res) => {
  try {
    const categoryIds = Array.isArray(req.body.category)
      ? req.body.category
      : [req.body.category];

    const categories = await Category.find({ _id: { $in: categoryIds } });
    if (!categories || categories.length === 0) {
      return res.status(400).json({ message: 'Invalid category ids' });
    }

    const provider = await Provider.findById(req.body.provider);
    if (!provider) {
      return res.status(400).json({ message: 'Invalid provider id' });
    }

    const productData = {
      // eslint-disable-next-line node/no-unsupported-features/es-syntax
      ...req.body,
      category: categories.map((cat) => cat._id),
      provider: provider._id,
    };

    const newProduct = await Product.create(productData);

    // Notify AI service to reload cache
    triggerAiReload();

    res.status(201).json({
      status: 'success',
      data: {
        product: newProduct,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: 'fail',
      message: err.message,
    });
  }
};

// Update a product
exports.updateProduct = async (req, res) => {
  try {
    const oldProduct = await Product.findById(req.params.id);
    if (!oldProduct) {
      return res.status(404).json({
        status: 'fail',
        message: 'Product not found',
      });
    }

    const updatedProduct = await Product.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true },
    );

    // Check for stock replenish (Back in Stock)
    if (req.body.stock > 0 && (!oldProduct.stock || oldProduct.stock <= 0)) {
      notifyPastBuyersProductBackInStock(updatedProduct).catch((err) =>
        console.error(
          'Failed to send back-in-stock notification (past buyers):',
          err.message,
        ),
      );
      notifyStockSubscribers(updatedProduct).catch((err) =>
        console.error(
          'Failed to send back-in-stock notification (subscribers):',
          err.message,
        ),
      );
    }

    // Notify AI service to reload cache (any data change)
    triggerAiReload();

    res.status(200).json({
      status: 'success',
      data: {
        product: updatedProduct,
      },
    });
  } catch (err) {
    res.status(500).json({
      status: 'fail',
      message: err.message,
    });
  }
};

// Delete a product
const { deleteProductFolder } = require('../config/cloudinary');

// ... (existing imports)

// Delete a product
exports.deleteProduct = async (req, res) => {
  try {
    // Delete product from MongoDB
    const product = await Product.findByIdAndDelete(req.params.id);

    if (!product) {
      return res.status(404).json({
        status: 'fail',
        message: 'No product found with that ID',
      });
    }

    // Delete associated images folder from Cloudinary
    try {
      await deleteProductFolder(req.params.id);
    } catch (imageError) {
      console.error(
        `Failed to delete images for product ${req.params.id}:`,
        imageError,
      );
      // We don't stop the response here, as the product is already deleted
    }

    res.status(204).json({
      status: 'success',
      data: null,
    });
  } catch (err) {
    res.status(404).json({
      status: 'fail',
      message: err.message,
    });
  }
};

// Get product statistics (Admin)
exports.getProductStats = async (req, res) => {
  try {
    const stats = await Product.aggregate([
      {
        $facet: {
          totalProducts: [{ $count: 'count' }],
          available: [{ $match: { stock: { $gt: 10 } } }, { $count: 'count' }],
          lowStock: [
            { $match: { stock: { $gt: 0, $lte: 10 } } },
            { $count: 'count' },
          ],
          outOfStock: [{ $match: { stock: 0 } }, { $count: 'count' }],
        },
      },
    ]);

    const result = {
      total:
        stats[0].totalProducts && stats[0].totalProducts[0]
          ? stats[0].totalProducts[0].count
          : 0,
      available:
        stats[0].available && stats[0].available[0]
          ? stats[0].available[0].count
          : 0,
      lowStock:
        stats[0].lowStock && stats[0].lowStock[0]
          ? stats[0].lowStock[0].count
          : 0,
      outOfStock:
        stats[0].outOfStock && stats[0].outOfStock[0]
          ? stats[0].outOfStock[0].count
          : 0,
    };

    res.status(200).json({
      status: 'success',
      data: result,
    });
  } catch (err) {
    res.status(500).json({
      status: 'fail',
      message: 'Error fetching product statistics',
    });
  }
};

// Get featured products
exports.getFeaturedProducts = async (req, res) => {
  try {
    const products = await Product.find({ isFeatured: true })
      .populate('category', 'nameAr _id')
      .populate('provider', 'storeName _id')
      .limit(20)
      .lean(); // Limit to 20 for performance (Home Page Carousel)

    res.status(200).json({
      status: 'success',
      results: products.length,
      data: {
        products,
      },
    });
  } catch (err) {
    res.status(500).json({
      status: 'fail',
      message: 'Error fetching featured products',
    });
  }
};

// Import products from Excel file
exports.importProducts = async (req, res) => {
  try {
    if (!req.file) {
      return res
        .status(400)
        .json({ status: 'fail', message: 'No file uploaded' });
    }

    const { preview } = req.query;
    const isPreview = preview === 'true';

    // Read from buffer instead of file path (for Vercel serverless)
    const workbook = xlsx.read(req.file.buffer, { type: 'buffer' });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const rows = xlsx.utils.sheet_to_json(worksheet);

    const newProducts = [];
    const updatedProducts = [];
    const missingProducts = [];
    const errors = [];

    // Pre-fetch all needed providers and categories to optimize
    // However, for simplicity and ensuring exact matches per row logic, we'll keep it loop-based
    // or we could optimize if performance becomes an issue.
    const isVendor = req.user.role === 'vendor';
    let vendorProvider = null;

    if (isVendor) {
      if (!req.user.provider) {
        return res.status(400).json({
          status: 'fail',
          message: 'Vendor user is not associated with any provider',
        });
      }
      // eslint-disable-next-line no-await-in-loop
      vendorProvider = await Provider.findById(req.user.provider);
      if (!vendorProvider) {
        return res.status(400).json({
          status: 'fail',
          message: 'Associated provider not found',
        });
      }
    }

    // Deduplicate rows: if the same barCode+provider combo appears more than once in the
    // sheet, only the LAST occurrence is processed (later row is the intended final version).
    const lastOccurrenceMap = new Map();
    rows.forEach((row, idx) => {
      const providerKey = isVendor
        ? '__vendor__'
        : row.provider
          ? row.provider.toString().trim()
          : '';
      const key = `${(row.barCode || '').toString().trim()}||${providerKey}`;
      lastOccurrenceMap.set(key, idx);
    });

    for (const [index, row] of rows.entries()) {
      try {
        // Skip rows superseded by a later row with the same barCode+provider combo
        const dupProviderKey = isVendor
          ? '__vendor__'
          : row.provider
            ? row.provider.toString().trim()
            : '';
        const dupKey = `${(row.barCode || '').toString().trim()}||${dupProviderKey}`;
        if (lastOccurrenceMap.get(dupKey) !== index) {
          // A later row covers this barCode+provider — skip this one
          // eslint-disable-next-line no-continue
          continue;
        }

        // ── DETECT MODE FIRST ──────────────────────────────────────────────────
        // A "category-only" sheet has just barCode + category and nothing else.
        // We must detect this BEFORE provider resolution so we don't block on it.
        const isCategoryOnlyUpdate =
          row.barCode &&
          row.category &&
          !row.nameAr &&
          !row.brand &&
          !row.provider &&
          !row.price;

        const hasPurchaseOrPrice =
          row.purchasePrice !== undefined || row.price !== undefined;

        const isPriceOnlyUpdate =
          row.barCode &&
          (hasPurchaseOrPrice || row.costPrice !== undefined) &&
          !row.nameAr &&
          !row.nameEn &&
          !row.brand &&
          !row.category &&
          !row.salePrice &&
          !row.stock &&
          !row.descriptionAr &&
          !row.descriptionEn &&
          !row.imageCover &&
          !row.images &&
          !row.isFeatured &&
          !row.ratingsAverage &&
          !row.ratingsQuantity;

        const isPriceOnlyMissingRequired =
          row.barCode &&
          !hasPurchaseOrPrice &&
          row.costPrice !== undefined &&
          !row.nameAr &&
          !row.nameEn &&
          !row.brand &&
          !row.category &&
          !row.salePrice &&
          !row.stock &&
          !row.descriptionAr &&
          !row.descriptionEn &&
          !row.imageCover &&
          !row.images &&
          !row.isFeatured &&
          !row.ratingsAverage &&
          !row.ratingsQuantity;

        const isImageOnlyUpdate =
          row.barCode &&
          row.imageCover &&
          !row.nameAr &&
          !row.nameEn &&
          !row.brand &&
          !row.category &&
          !row.price &&
          !row.purchasePrice &&
          !row.costPrice &&
          !row.salePrice &&
          !row.stock &&
          !row.descriptionAr &&
          !row.descriptionEn &&
          !row.images &&
          !row.isFeatured &&
          !row.ratingsAverage &&
          !row.ratingsQuantity;

        const isBroadBarcodeUpdate =
          !isVendor &&
          (isCategoryOnlyUpdate ||
            (isPriceOnlyUpdate && !row.provider) ||
            (isImageOnlyUpdate && !row.provider));

        if (isPriceOnlyMissingRequired) {
          errors.push({
            row: index + 2,
            message:
              'Price-only update requires purchasePrice or price (costPrice is optional)',
            name: row.nameAr || 'Unknown',
          });
          // eslint-disable-next-line no-continue
          continue;
        }

        if (isPriceOnlyMissingRequired) {
          errors.push({
            row: index + 2,
            message:
              'Price-only update requires purchasePrice or price (costPrice is optional)',
            name: row.nameAr || 'Unknown',
          });
          // eslint-disable-next-line no-continue
          continue;
        }

        // 1. Resolve Provider (skipped entirely for category-only updates)
        let provider = vendorProvider;
        if (!isVendor && !isCategoryOnlyUpdate) {
          const pIdentifier = row.provider
            ? row.provider.toString().trim()
            : '';
          let foundProvider = null;

          if (/^\d+$/.test(pIdentifier)) {
            foundProvider = await Provider.findOne({ id: Number(pIdentifier) });
          }

          if (!foundProvider && mongoose.Types.ObjectId.isValid(pIdentifier)) {
            foundProvider = await Provider.findById(pIdentifier);
          }

          if (!foundProvider) {
            foundProvider = await Provider.findOne({
              $or: [{ storeName: pIdentifier }, { name: pIdentifier }],
            });
          }

          provider = foundProvider;

          if (!provider) {
            errors.push({
              row: index + 2,
              message: `Invalid provider: ${row.provider}`,
              name: row.nameAr || 'Unknown',
            });
            // eslint-disable-next-line no-continue
            continue;
          }
        }

        // Validation: Required fields only for NEW products or full-row updates
        // For partial/category-only updates, barcode alone is enough to find the product
        const hasMissingFields =
          isCategoryOnlyUpdate || isPriceOnlyUpdate || isImageOnlyUpdate
            ? false // skip full validation for partial updates
            : isVendor
              ? !row.barCode || !row.nameAr || !row.brand || !row.category
              : !row.barCode ||
                !row.nameAr ||
                !row.brand ||
                !row.category ||
                !row.provider;

        if (hasMissingFields) {
          errors.push({
            row: index + 2,
            message: isVendor
              ? 'Missing required fields: Barcode, Name, Brand, or Category'
              : 'Missing required fields: Barcode, Name, Brand, Category, or Provider',
          });
          // eslint-disable-next-line no-continue
          continue;
        }

        // Search for existing product(s) by barcode.
        // For category-only updates: find ALL products with this barcode (across all providers)
        // For full updates: find by barcode+provider to enforce uniqueness per provider
        // eslint-disable-next-line no-await-in-loop
        const existingProducts = isBroadBarcodeUpdate
          ? await Product.find({ barCode: row.barCode.toString().trim() })
          : null;

        // eslint-disable-next-line no-await-in-loop
        const existingProduct = isBroadBarcodeUpdate
          ? existingProducts && existingProducts.length > 0
            ? existingProducts[0]
            : null
          : await Product.findOne({
              barCode: row.barCode,
              provider: provider._id,
            });

        // (Redundant but safe: If vendor, they only see products for their own provider anyway due to search above)
        if (
          existingProduct &&
          isVendor &&
          !existingProduct.provider.equals(vendorProvider._id)
        ) {
          errors.push({
            row: index + 2,
            message:
              'You do not have permission to update this product (belongs to another provider)',
            name: row.nameAr,
          });
          // eslint-disable-next-line no-continue
          continue;
        }

        if (existingProduct) {
          if (isPriceOnlyUpdate) {
            const normalizedBarcode = row.barCode.toString().trim();
            const nextPurchasePrice =
              row.purchasePrice !== undefined && row.purchasePrice !== null
                ? Number(row.purchasePrice) || 0
                : undefined;
            const nextCostPrice =
              row.costPrice !== undefined && row.costPrice !== null
                ? Number(row.costPrice) || 0
                : undefined;
            const nextPrice =
              row.price !== undefined && row.price !== null
                ? Number(row.price) || 0
                : undefined;

            if (isPreview) {
              updatedProducts.push({
                barCode: normalizedBarcode,
                changes: {
                  ...(nextPurchasePrice !== undefined
                    ? {
                        purchasePrice: {
                          old: existingProduct.purchasePrice,
                          new: nextPurchasePrice,
                        },
                      }
                    : {}),
                  ...(nextCostPrice !== undefined
                    ? {
                        costPrice: {
                          old: existingProduct.costPrice,
                          new: nextCostPrice,
                        },
                      }
                    : {}),
                  ...(nextPrice !== undefined
                    ? {
                        price: {
                          old: existingProduct.price,
                          new: nextPrice,
                        },
                      }
                    : {}),
                },
                providerName:
                  (provider && provider.storeName) || 'All Providers',
              });
            } else {
              const updateFields = {};
              if (nextPurchasePrice !== undefined)
                updateFields.purchasePrice = nextPurchasePrice;
              if (nextCostPrice !== undefined)
                updateFields.costPrice = nextCostPrice;
              if (nextPrice !== undefined) updateFields.price = nextPrice;

              if (isBroadBarcodeUpdate) {
                // eslint-disable-next-line no-await-in-loop
                await Product.updateMany(
                  { barCode: normalizedBarcode },
                  { $set: updateFields },
                );
              } else {
                // eslint-disable-next-line no-await-in-loop
                await Product.findByIdAndUpdate(existingProduct._id, {
                  $set: updateFields,
                });
              }

              updatedProducts.push(normalizedBarcode);
            }

            // eslint-disable-next-line no-continue
            continue;
          }

          if (isImageOnlyUpdate) {
            const normalizedBarcode = row.barCode.toString().trim();

            if (isPreview) {
              updatedProducts.push({
                barCode: normalizedBarcode,
                changes: {
                  imageCover: {
                    old: existingProduct.imageCover,
                    new: row.imageCover,
                  },
                },
                providerName:
                  (provider && provider.storeName) || 'All Providers',
              });
            } else {
              if (isBroadBarcodeUpdate) {
                // eslint-disable-next-line no-await-in-loop
                const productsToUpdate = await Product.find({
                  barCode: normalizedBarcode,
                });

                for (const product of productsToUpdate) {
                  // eslint-disable-next-line no-await-in-loop
                  const newCover = await uploadExternalImage(
                    row.imageCover,
                    product._id,
                    true,
                  );

                  if (newCover) {
                    // eslint-disable-next-line no-await-in-loop
                    await Product.findByIdAndUpdate(product._id, {
                      $set: { imageCover: newCover },
                    });

                    if (
                      product.imageCover &&
                      product.imageCover !== newCover
                    ) {
                      // eslint-disable-next-line no-await-in-loop
                      await deleteCloudinaryImage(product.imageCover);
                    }
                  }
                }
              } else {
                // eslint-disable-next-line no-await-in-loop
                const newCover = await uploadExternalImage(
                  row.imageCover,
                  existingProduct._id,
                  true,
                );

                if (newCover) {
                  // eslint-disable-next-line no-await-in-loop
                  await Product.findByIdAndUpdate(existingProduct._id, {
                    $set: { imageCover: newCover },
                  });

                  if (
                    existingProduct.imageCover &&
                    existingProduct.imageCover !== newCover
                  ) {
                    // eslint-disable-next-line no-await-in-loop
                    await deleteCloudinaryImage(existingProduct.imageCover);
                  }
                }
              }

              updatedProducts.push(normalizedBarcode);
            }

            // eslint-disable-next-line no-continue
            continue;
          }

          // EXISTING PRODUCT: Update all fields
          // SMART CATEGORY RESOLUTION
          const rawCategoryValue = (row.category || '').toString().trim();
          const categoryIdentifiers = rawCategoryValue
            ? [
                ...new Set(
                  rawCategoryValue
                    .split(',')
                    .map((val) => val.trim())
                    .filter(Boolean),
                ),
              ]
            : [];

          const categoryObjectIds = [];
          const categoryNamesForPreview = [];

          for (const identifier of categoryIdentifiers) {
            let foundCategory = null;

            // 1. Try Numeric ID
            if (/^\d+$/.test(identifier)) {
              foundCategory = await Category.findOne({
                id: Number(identifier),
              });
            }

            // 2. Try ObjectId
            if (!foundCategory && mongoose.Types.ObjectId.isValid(identifier)) {
              foundCategory = await Category.findById(identifier);
            }

            // 3. Try Name (Ar/En) or Slug
            if (!foundCategory) {
              foundCategory = await Category.findOne({
                $or: [
                  { nameAr: identifier },
                  { nameEn: identifier },
                  { slug: identifier },
                ],
              });
            }

            if (foundCategory) {
              categoryObjectIds.push(foundCategory._id);
              categoryNamesForPreview.push(foundCategory.nameAr);
            }
          }

          // Validation: Ensure at least one category is found
          if (
            categoryIdentifiers.length > 0 &&
            categoryObjectIds.length === 0
          ) {
            errors.push({
              row: index + 2,
              message: `None of the provided category identifiers were found: ${row.category}`,
              name: row.nameAr,
            });
            // eslint-disable-next-line no-continue
            continue;
          }

          // SMART BRAND RESOLUTION
          let brandName = row.brand;
          if (row.brand) {
            let foundBrand = null;
            const bIdentifier = row.brand.toString().trim();

            if (/^\d+$/.test(bIdentifier)) {
              foundBrand = await Brand.findOne({ id: Number(bIdentifier) });
            }

            if (!foundBrand && mongoose.Types.ObjectId.isValid(bIdentifier)) {
              foundBrand = await Brand.findById(bIdentifier);
            }

            if (!foundBrand) {
              foundBrand = await Brand.findOne({
                $or: [
                  { nameEn: bIdentifier },
                  { nameAr: bIdentifier },
                  { slug: bIdentifier },
                ],
              });
            }

            if (foundBrand) brandName = foundBrand.nameEn;
          }

          // Handle Image Uploads to Cloudinary (ONLY if not preview)
          let finalImageCover = row.imageCover || existingProduct.imageCover;
          let finalImages = row.images
            ? row.images.split(',')
            : existingProduct.images || [];

          if (!isPreview) {
            if (row.imageCover) {
              // eslint-disable-next-line no-await-in-loop
              finalImageCover = await uploadExternalImage(
                row.imageCover,
                existingProduct._id,
                true,
              );
            }

            if (row.images) {
              const imgArray = row.images.split(',');
              // eslint-disable-next-line no-await-in-loop
              finalImages = await Promise.all(
                imgArray.map((img) =>
                  uploadExternalImage(img.trim(), existingProduct._id, false),
                ),
              );

              finalImages = finalImages.filter(Boolean);

              // Delete any old extra images that are no longer in the updated list
              if (finalImages.length > 0) {
                const oldImages = existingProduct.images || [];
                for (const oldImg of oldImages) {
                  if (oldImg && !finalImages.includes(oldImg)) {
                    // eslint-disable-next-line no-await-in-loop
                    await deleteCloudinaryImage(oldImg);
                  }
                }
              }
            }

            // Keep updates resilient: use first valid gallery image, otherwise keep old cover.
            if (!finalImageCover && finalImages.length > 0) {
              [finalImageCover] = finalImages;
            }
            if (!finalImageCover) {
              // eslint-disable-next-line no-await-in-loop
              const existingCoverIsReachable = await isImageUrlReachable(
                existingProduct.imageCover,
              );
              finalImageCover = existingCoverIsReachable
                ? existingProduct.imageCover
                : IMPORT_FALLBACK_COVER_IMAGE;
            }

            // If cover changed, cleanup old cover on our Cloudinary cloud.
            if (
              finalImageCover &&
              existingProduct.imageCover &&
              existingProduct.imageCover !== finalImageCover
            ) {
              // eslint-disable-next-line no-await-in-loop
              await deleteCloudinaryImage(existingProduct.imageCover);
            }
          }

          // PARTIAL UPDATE: Only include fields that are present in the Excel row
          const updateData = {};

          // Category is always updated when provided (required for category-only mode)
          if (categoryObjectIds.length > 0)
            updateData.category = categoryObjectIds;

          // Only update other fields if they are actually present in the row
          if (
            row.nameEn !== undefined &&
            row.nameEn !== null &&
            row.nameEn !== ''
          )
            updateData.nameEn = row.nameEn;
          if (
            row.nameAr !== undefined &&
            row.nameAr !== null &&
            row.nameAr !== ''
          )
            updateData.nameAr = row.nameAr;
          if (row.descriptionEn)
            updateData.descriptionEn = row.descriptionEn.split(',');
          if (row.descriptionAr)
            updateData.descriptionAr = row.descriptionAr.split(',');
          if (brandName && row.brand) updateData.brand = brandName;
          if (provider) updateData.provider = provider._id;
          if (row.stock !== undefined && row.stock !== null && row.stock !== '')
            updateData.stock = Number(row.stock) || 0;
          if (
            row.isFeatured !== undefined &&
            row.isFeatured !== null &&
            row.isFeatured !== ''
          )
            updateData.isFeatured = Boolean(Number(row.isFeatured));
          if (row.price !== undefined && row.price !== null && row.price !== '')
            updateData.price = Number(row.price) || 0;
          if (
            row.purchasePrice !== undefined &&
            row.purchasePrice !== null &&
            row.purchasePrice !== ''
          )
            updateData.purchasePrice = Number(row.purchasePrice) || 0;
          if (
            row.salePrice !== undefined &&
            row.salePrice !== null &&
            row.salePrice !== ''
          )
            updateData.salePrice = Number(row.salePrice) || 0;
          if (row.ratingsAverage !== undefined && row.ratingsAverage !== '')
            updateData.ratingsAverage = Number(row.ratingsAverage) || 0;
          if (row.ratingsQuantity !== undefined && row.ratingsQuantity !== '')
            updateData.ratingsQuantity = Number(row.ratingsQuantity) || 0;
          if (finalImageCover) updateData.imageCover = finalImageCover;
          if (finalImages && finalImages.length > 0)
            updateData.images = finalImages;

          if (isPreview) {
            // Calculate changes for preview — only show fields that are actually in updateData
            const changes = {};
            if (
              'nameAr' in updateData &&
              existingProduct.nameAr !== updateData.nameAr
            )
              changes.nameAr = {
                old: existingProduct.nameAr,
                new: updateData.nameAr,
              };
            if (
              'nameEn' in updateData &&
              existingProduct.nameEn !== updateData.nameEn
            )
              changes.nameEn = {
                old: existingProduct.nameEn,
                new: updateData.nameEn,
              };
            if (
              'price' in updateData &&
              existingProduct.price !== updateData.price
            )
              changes.price = {
                old: existingProduct.price,
                new: updateData.price,
              };
            if (
              'purchasePrice' in updateData &&
              existingProduct.purchasePrice !== updateData.purchasePrice
            )
              changes.purchasePrice = {
                old: existingProduct.purchasePrice,
                new: updateData.purchasePrice,
              };
            if (
              'salePrice' in updateData &&
              existingProduct.salePrice !== updateData.salePrice
            )
              changes.salePrice = {
                old: existingProduct.salePrice,
                new: updateData.salePrice,
              };
            if (
              'stock' in updateData &&
              existingProduct.stock !== updateData.stock
            )
              changes.stock = {
                old: existingProduct.stock,
                new: updateData.stock,
              };
            if (
              'brand' in updateData &&
              existingProduct.brand !== updateData.brand
            )
              changes.brand = {
                old: existingProduct.brand,
                new: updateData.brand,
              };
            if ('category' in updateData)
              changes.category = {
                old: '(previous)',
                new: categoryNamesForPreview.join(', '),
              };

            updatedProducts.push({
              nameAr: updateData.nameAr || existingProduct.nameAr,
              barCode: row.barCode,
              changes,
              categoryNames: categoryNamesForPreview.join(', '),
              providerName: (provider && provider.storeName) || 'All Providers',
            });
          } else if (isCategoryOnlyUpdate) {
            // CATEGORY-ONLY: update ALL products with this barcode across all providers
            // eslint-disable-next-line no-await-in-loop
            await Product.updateMany(
              { barCode: row.barCode.toString().trim() },
              { $set: { category: categoryObjectIds } },
            );
            updatedProducts.push(row.barCode);
          } else {
            // Update single product (full update path)
            // eslint-disable-next-line no-await-in-loop
            const updatedProd = await Product.findByIdAndUpdate(
              existingProduct._id,
              { $set: updateData },
              { new: true },
            );

            // Check if restocked
            if (
              updateData.stock > 0 &&
              (!existingProduct.stock || existingProduct.stock <= 0)
            ) {
              notifyPastBuyersProductBackInStock(updatedProd).catch((err) =>
                console.error(
                  'Failed to send back-in-stock notification during import:',
                  err.message,
                ),
              );
            }

            updatedProducts.push(existingProduct.barCode);
          }
        } else {
          if (isPriceOnlyUpdate) {
            missingProducts.push({
              row: index + 2,
              barCode: row.barCode.toString().trim(),
              provider: row.provider ? row.provider.toString().trim() : '',
              purchasePrice:
                row.purchasePrice !== undefined && row.purchasePrice !== null
                  ? Number(row.purchasePrice) || 0
                  : undefined,
              costPrice:
                row.costPrice !== undefined && row.costPrice !== null
                  ? Number(row.costPrice) || 0
                  : undefined,
              price:
                row.price !== undefined && row.price !== null
                  ? Number(row.price) || 0
                  : undefined,
            });
            // eslint-disable-next-line no-continue
            continue;
          }

          if (isImageOnlyUpdate) {
            missingProducts.push({
              row: index + 2,
              barCode: row.barCode.toString().trim(),
              provider: row.provider ? row.provider.toString().trim() : '',
              imageCover: row.imageCover || '',
            });
            // eslint-disable-next-line no-continue
            continue;
          }

          // NEW PRODUCT: Create
          // SMART CATEGORY RESOLUTION (NEW PRODUCT)
          const rawCategoryValueNew = (row.category || '').toString().trim();
          const categoryIdentifiersNew = rawCategoryValueNew
            ? [
                ...new Set(
                  rawCategoryValueNew
                    .split(',')
                    .map((val) => val.trim())
                    .filter(Boolean),
                ),
              ]
            : [];

          const categoryObjectIdsNew = [];
          const categoryNamesForPreviewNew = [];

          for (const identifier of categoryIdentifiersNew) {
            let foundCategory = null;

            if (/^\d+$/.test(identifier)) {
              foundCategory = await Category.findOne({
                id: Number(identifier),
              });
            }

            if (!foundCategory && mongoose.Types.ObjectId.isValid(identifier)) {
              foundCategory = await Category.findById(identifier);
            }

            if (!foundCategory) {
              foundCategory = await Category.findOne({
                $or: [
                  { nameAr: identifier },
                  { nameEn: identifier },
                  { slug: identifier },
                ],
              });
            }

            if (foundCategory) {
              categoryObjectIdsNew.push(foundCategory._id);
              categoryNamesForPreviewNew.push(foundCategory.nameAr);
            }
          }

          if (
            categoryIdentifiersNew.length > 0 &&
            categoryObjectIdsNew.length === 0
          ) {
            errors.push({
              row: index + 2,
              message: `None of the provided category identifiers were found: ${row.category}`,
              name: row.nameAr,
            });
            // eslint-disable-next-line no-continue
            continue;
          }

          // SMART BRAND RESOLUTION (NEW PRODUCT)
          let brandNameForNew = row.brand;
          if (row.brand) {
            let foundBrand = null;
            const bIdentifier = row.brand.toString().trim();

            if (/^\d+$/.test(bIdentifier)) {
              foundBrand = await Brand.findOne({ id: Number(bIdentifier) });
            }

            if (!foundBrand && mongoose.Types.ObjectId.isValid(bIdentifier)) {
              foundBrand = await Brand.findById(bIdentifier);
            }

            if (!foundBrand) {
              foundBrand = await Brand.findOne({
                $or: [
                  { nameEn: bIdentifier },
                  { nameAr: bIdentifier },
                  { slug: bIdentifier },
                ],
              });
            }

            if (foundBrand) brandNameForNew = foundBrand.nameEn;
          }

          // Generate potential ID for new product to use in folder name
          const newProductId = new mongoose.Types.ObjectId();

          // Handle Image Uploads to Cloudinary (ONLY if not preview)
          let finalImageCoverNew = row.imageCover;
          let finalImagesNew = row.images ? row.images.split(',') : [];

          if (!isPreview) {
            if (row.imageCover) {
              // eslint-disable-next-line no-await-in-loop
              finalImageCoverNew = await uploadExternalImage(
                row.imageCover,
                newProductId,
                true,
              );
            }

            if (row.images) {
              const imgArray = row.images.split(',');
              // eslint-disable-next-line no-await-in-loop
              finalImagesNew = await Promise.all(
                imgArray.map((img) =>
                  uploadExternalImage(img.trim(), newProductId, false),
                ),
              );
            }

            // Ensure new products always have a valid cover image to satisfy schema validation.
            finalImagesNew = finalImagesNew.filter(Boolean);
            if (!finalImageCoverNew && finalImagesNew.length > 0) {
              [finalImageCoverNew] = finalImagesNew;
            }
            if (!finalImageCoverNew) {
              finalImageCoverNew = IMPORT_FALLBACK_COVER_IMAGE;
            }
          }

          const productData = {
            _id: newProductId,
            nameEn: row.nameEn,
            nameAr: row.nameAr,
            descriptionEn: row.descriptionEn
              ? row.descriptionEn.split(',')
              : [],
            descriptionAr: row.descriptionAr
              ? row.descriptionAr.split(',')
              : [],
            barCode: row.barCode,
            brand: brandNameForNew,
            category: categoryObjectIdsNew,
            provider: provider._id,
            stock: Number(row.stock) || 0,
            isFeatured: Boolean(Number(row.isFeatured)),
            price: Number(row.price) || 0,
            purchasePrice: Number(row.purchasePrice) || 0,
            salePrice: Number(row.salePrice) || 0,
            ratingsAverage: Number(row.ratingsAverage) || 0,
            ratingsQuantity: Number(row.ratingsQuantity) || 0,
            imageCover: finalImageCoverNew,
            images: finalImagesNew,
          };

          if (isPreview) {
            newProducts.push({
              ...productData,
              categoryNames: categoryNamesForPreviewNew.join(', '),
              providerName: provider.storeName,
            });
          } else {
            // eslint-disable-next-line no-await-in-loop
            await Product.create(productData);
            newProducts.push(row.barCode);
          }
        }
      } catch (err) {
        errors.push({
          row: index + 2,
          message: err.message,
          name: row.nameAr || 'Unknown',
        });
      }
    }

    // No file cleanup needed - using memory storage

    const { missingExport } = req.query;
    const shouldExportMissing =
      missingExport === 'true' && missingProducts.length > 0;

    if (shouldExportMissing) {
      const templateRows = missingProducts.map((item) => ({
        barCode: item.barCode || '',
        provider: item.provider || '',
        purchasePrice:
          item.purchasePrice !== undefined ? item.purchasePrice : '',
        costPrice: item.costPrice !== undefined ? item.costPrice : '',
        price: item.price !== undefined ? item.price : '',
        nameAr: '',
        nameEn: '',
        brand: '',
        category: '',
        stock: '',
        imageCover: '',
        images: '',
      }));

      const workbook = xlsx.utils.book_new();
      const worksheet = xlsx.utils.json_to_sheet(templateRows);
      xlsx.utils.book_append_sheet(workbook, worksheet, 'MissingProducts');

      const buffer = xlsx.write(workbook, { type: 'buffer', bookType: 'xlsx' });

      res.setHeader(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      );
      res.setHeader(
        'Content-Disposition',
        `attachment; filename=missing-products-${Date.now()}.xlsx`,
      );

      res.send(buffer);
      return;
    }

    res.status(200).json({
      status: 'success',
      mode: isPreview ? 'preview' : 'execute',
      summary: {
        newCount: newProducts.length,
        updatedCount: updatedProducts.length,
        missingCount: missingProducts.length,
        errorsCount: errors.length,
      },
      data: {
        newProducts,
        updatedProducts,
        missingProducts,
        errors,
      },
    });

    // Notify AI service to reload cache after batch import
    if (!isPreview && (newProducts.length > 0 || updatedProducts.length > 0)) {
      triggerAiReload();
    }
  } catch (error) {
    // No file cleanup needed - using memory storage

    console.error(error);
    res.status(500).json({
      status: 'error',
      message: 'Something went wrong',
      error: error.message,
    });
  }
};

// Export products to Excel file
exports.exportProducts = async (req, res) => {
  try {
    const isVendor = req.user.role === 'vendor';
    const query = {};

    if (isVendor) {
      if (!req.user.provider) {
        return res.status(400).json({
          status: 'fail',
          message: 'Vendor user is not associated with any provider',
        });
      }
      query.provider = req.user.provider;
    }

    // Add category filter if provided
    if (req.query.category) {
      query.category = req.query.category;
    }

    // Add brand filter if provided
    if (req.query.brand) {
      query.brand = req.query.brand;
    }

    // Fetch products with populated category and provider
    const products = await Product.find(query)
      .populate('category', 'id nameAr nameEn')
      .populate('provider', 'id storeName');

    // Prepare data for Excel
    const excelData = products.map((product) => ({
      nameEn: product.nameEn || '',
      nameAr: product.nameAr || '',
      descriptionEn: product.descriptionEn
        ? product.descriptionEn.join(',')
        : '',
      descriptionAr: product.descriptionAr
        ? product.descriptionAr.join(',')
        : '',
      barCode: product.barCode || '',
      brand:
        typeof product.brand === 'string' &&
        /^[0-9a-fA-F]{24}$/.test(product.brand)
          ? product.brand
          : product.brand || '',
      category:
        product.category && product.category.length > 0
          ? product.category.map((cat) => cat.id).join(',')
          : '',
      provider: product.provider ? product.provider.id : '',
      stock: product.stock || 0,
      isFeatured: product.isFeatured ? 1 : 0,
      price: product.price || 0,
      purchasePrice: product.purchasePrice || 0,
      salePrice: product.salePrice || 0,
      ratingsAverage: product.ratingsAverage || 0,
      ratingsQuantity: product.ratingsQuantity || 0,
      imageCover: product.imageCover || '',
      images:
        product.images && product.images.length > 0
          ? product.images.join(',')
          : '',
    }));

    // Create workbook and worksheet
    const workbook = xlsx.utils.book_new();
    const worksheet = xlsx.utils.json_to_sheet(excelData);

    // Add worksheet to workbook
    xlsx.utils.book_append_sheet(workbook, worksheet, 'Products');

    // Generate buffer
    const buffer = xlsx.write(workbook, { type: 'buffer', bookType: 'xlsx' });

    // Set headers for file download
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=products-export-${Date.now()}.xlsx`,
    );

    // Send file
    res.send(buffer);
  } catch (error) {
    console.error('Export error:', error);
    res.status(500).json({
      status: 'error',
      message: 'Failed to export products',
      error: error.message,
    });
  }
};

// Generate Facebook Product Catalog XML Feed
exports.getFacebookCatalog = async (req, res) => {
  try {
    // 1. Fetch products (limit to in-stock or all? Facebook usually wants all with availability status)
    const products = await Product.find()
      .populate('category', 'nameAr nameEn')
      .populate('brand', 'nameEn nameAr')
      .limit(2000); // Increased limit for Meta catalog

    // 2. Format as RSS 2.0 (Facebook XML standard)
    const frontendUrl = (
      process.env.FRONTEND_URL || 'https://www.samoulla.com'
    ).replace(/\/$/, '');

    let xml = `<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <title>Samoulla Product Catalog</title>
    <link>${frontendUrl}</link>
    <description>Quality tools, hardware, and equipment from Samoulla</description>`;

    products.forEach((product) => {
      const id = product._id.toString();
      const title = (product.nameEn || product.nameAr || '').replace(
        /[&<>"']/g,
        (m) =>
          ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&apos;',
          })[m],
      );
      const description = (
        (product.descriptionEn && product.descriptionEn[0]) ||
        (product.descriptionAr && product.descriptionAr[0]) ||
        title
      ).replace(
        /[&<>"']/g,
        (m) =>
          ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&apos;',
          })[m],
      );
      const link = `${frontendUrl}/product/${product.slug || id}`;
      const imageLink = product.imageCover || '';
      const price = `${product.price} EGP`;
      const availability = product.stock > 0 ? 'in stock' : 'out of stock';
      const brand = (product.brand || 'Samoulla').replace(
        /[&<>"']/g,
        (m) =>
          ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&apos;',
          })[m],
      );
      const categoryName =
        (product.category &&
          product.category[0] &&
          product.category[0].nameEn) ||
        'Tools & Equipment';
      const category = categoryName.replace(
        /[&<>"']/g,
        (m) =>
          ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&apos;',
          })[m],
      );

      xml += `
    <item>
      <g:id>${id}</g:id>
      <g:title>${title}</g:title>
      <g:description>${description}</g:description>
      <g:link>${link}</g:link>
      <g:image_link>${imageLink}</g:image_link>
      <g:condition>new</g:condition>
      <g:availability>${availability}</g:availability>
      <g:price>${price}</g:price>
      <g:brand>${brand}</g:brand>
      <g:google_product_category>${category}</g:google_product_category>
    </item>`;
    });

    xml += `
  </channel>
</rss>`;

    // 3. Send response with XML header
    res.set('Content-Type', 'text/xml');
    res.status(200).send(xml);
  } catch (error) {
    console.error('Facebook Catalog Error:', error);
    res.status(500).json({
      status: 'error',
      message: 'Failed to generate catalog',
    });
  }
};