summaryrefslogtreecommitdiff
path: root/lib/vendors/service.ts
blob: 7c8df1a63baba7a1e51cda8fa27f0f3de7524fb8 (plain)
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
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택)

import { revalidateTag, unstable_noStore } from "next/cache";
import db from "@/db/db";
import { vendorAttachments, VendorContact, vendorContacts, vendorDetailView, vendorItemsView, vendorMaterialsView, vendorPossibleItems, vendorPossibleMateirals, vendors, vendorsWithTypesView, vendorTypes, type Vendor } from "@/db/schema";
import logger from '@/lib/logger';
import * as z from "zod"

import { filterColumns } from "@/lib/filter-columns";
import { unstable_cache } from "@/lib/unstable-cache";
import { getErrorMessage } from "@/lib/handle-error";
import { headers } from 'next/headers';

import {
  selectVendors,
  countVendors,
  insertVendor,
  updateVendor,
  updateVendors, groupByStatus,
  getVendorById,
  getVendorContactsById,
  selectVendorContacts,
  countVendorContacts,
  insertVendorContact,
  selectVendorItems,
  countVendorItems,
  insertVendorItem,
  countRfqHistory,
  selectRfqHistory,
  selectVendorsWithTypes,
  countVendorsWithTypes,
  countVendorMaterials,
  selectVendorMaterials,
  insertVendorMaterial,

} from "./repository";

import type {
  CreateVendorSchema,
  UpdateVendorSchema,
  GetVendorsSchema,
  GetVendorContactsSchema,
  CreateVendorContactSchema,
  GetVendorItemsSchema,
  CreateVendorItemSchema,
  GetRfqHistorySchema,
  GetVendorMaterialsSchema,
} from "./validations";

import { asc, desc, ilike, inArray, and, or, gte, lte, eq, isNull, count, sql } from "drizzle-orm";
import { rfqItems, rfqs, vendorRfqView } from "@/db/schema/rfq";
import path from "path";
import { sendEmail } from "../mail/sendEmail";
import { PgTransaction } from "drizzle-orm/pg-core";
import { items, materials } from "@/db/schema/items";
import { roles, userRoles, users } from "@/db/schema/users";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { contracts, contractsDetailView, projects, vendorPQSubmissions, vendorProjectPQs, vendorsLogs } from "@/db/schema";
import { deleteFile, saveFile } from "../file-stroage";


/* -----------------------------------------------------
   1) 조회 관련 
----------------------------------------------------- */

/**
 * 복잡한 조건으로 Vendor 목록을 조회 (+ pagination) 하고,
 * 총 개수에 따라 pageCount를 계산해서 리턴.
 * Next.js의 unstable_cache를 사용해 일정 시간 캐시.
 */
export async function getVendors(input: GetVendorsSchema) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;
        
        // 1) 고급 필터 - vendors 대신 vendorsWithTypesView 사용
        const advancedWhere = filterColumns({
          table: vendorsWithTypesView,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });
        
        // 2) 글로벌 검색
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(vendorsWithTypesView.vendorName, s),
            ilike(vendorsWithTypesView.vendorCode, s),
            ilike(vendorsWithTypesView.email, s),
            ilike(vendorsWithTypesView.status, s),
            // 추가: 업체 유형 검색
            ilike(vendorsWithTypesView.vendorTypeName, s)
          );
        }
        
        // 최종 where 결합
        const finalWhere = and(advancedWhere, globalWhere);
        
        // 간단 검색 (advancedTable=false) 시 예시
        const simpleWhere = and(
          input.vendorName
            ? ilike(vendorsWithTypesView.vendorName, `%${input.vendorName}%`)
            : undefined,
          input.status ? ilike(vendorsWithTypesView.status, input.status) : undefined,
          input.country
            ? ilike(vendorsWithTypesView.country, `%${input.country}%`)
            : undefined
        );
        
        // 실제 사용될 where
        const where = finalWhere;
        
        // 정렬
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(vendorsWithTypesView[item.id]) : asc(vendorsWithTypesView[item.id])
            )
            : [asc(vendorsWithTypesView.createdAt)];
        
        // 트랜잭션 내에서 데이터 조회
        const { data, total } = await db.transaction(async (tx) => {
          // 1) vendor 목록 조회 (view 사용)
          const vendorsData = await selectVendorsWithTypes(tx, {
            where,
            orderBy,
            offset,
            limit: input.perPage,
          });
          
          // 2) 각 vendor의 attachments 조회
          const vendorsWithAttachments = await Promise.all(
            vendorsData.map(async (vendor) => {
              const attachments = await tx
                .select({
                  id: vendorAttachments.id,
                  fileName: vendorAttachments.fileName,
                  filePath: vendorAttachments.filePath,
                })
                .from(vendorAttachments)
                .where(eq(vendorAttachments.vendorId, vendor.id));
              
              return {
                ...vendor,
                hasAttachments: attachments.length > 0,
                attachmentsList: attachments,
              };
            })
          );
          
          // 3) 전체 개수
          const total = await countVendorsWithTypes(tx, where);
          return { data: vendorsWithAttachments, total };
        });

        console.log(total)
        
        // 페이지 수
        const pageCount = Math.ceil(total / input.perPage);
        
        return { data, pageCount };
      } catch (err) {
        console.error("Error fetching vendors:", err);
        // 에러 발생 시
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input)], // 캐싱 키
    {
      revalidate: 3600,
      tags: ["vendors"], // revalidateTag("vendors") 호출 시 무효화
    }
  )();
}

export async function getVendorStatusCounts() {
  return unstable_cache(
    async () => {
      try {

        const initial: Record<Vendor["status"], number> = {
          ACTIVE: 0,
          INACTIVE: 0,
          BLACKLISTED: 0,
          "PENDING_REVIEW": 0,
          "IN_REVIEW": 0,
          "REJECTED": 0,
          "IN_PQ": 0,
          "PQ_FAILED": 0,
          "PQ_APPROVED": 0,
          "APPROVED": 0,
          "READY_TO_SEND": 0,
          "PQ_SUBMITTED": 0
        };


        const result = await db.transaction(async (tx) => {
          const rows = await groupByStatus(tx);
          return rows.reduce<Record<Vendor["status"], number>>((acc, { status, count }) => {
            acc[status] = count;
            return acc;
          }, initial);
        });

        return result;
      } catch (err) {
        return {} as Record<Vendor["status"], number>;
      }
    },
    ["task-status-counts"], // 캐싱 키
    {
      revalidate: 3600,
    }
  )();
}

/* -----------------------------------------------------
   2) 생성(Create) 
----------------------------------------------------- */

/**
 * 신규 Vendor 생성
 */

async function storeVendorFiles(
  tx: PgTransaction<any, any, any>,
  vendorId: number,
  files: File[],
  attachmentType: string
) {
 

  for (const file of files) {

    const saveResult = await saveFile({file, directory:`vendors/${vendorId}` })

    // Insert attachment record
    await tx.insert(vendorAttachments).values({
      vendorId,
      fileName: file.name,
      filePath: saveResult.publicPath,
      attachmentType, // "GENERAL", "CREDIT_RATING", "CASH_FLOW_RATING", ...
    })
  }
}


export async function getVendorTypes() {
  unstable_noStore(); // Next.js server action caching prevention
  
  try {
    const types = await db
      .select({
        id: vendorTypes.id,
        code: vendorTypes.code,
        nameKo: vendorTypes.nameKo,
        nameEn: vendorTypes.nameEn,
      })
      .from(vendorTypes)
      .orderBy(vendorTypes.nameKo);
    
    return { data: types, error: null };
  } catch (error) {
    return { data: null, error: getErrorMessage(error) };
  }
}

export type CreateVendorData = {
  vendorName: string
  vendorTypeId: number
  vendorCode?: string
  items?: string
  website?: string
  taxId: string
  address?: string
  email: string
  phone?: string
  
  representativeName?: string
  representativeBirth?: string
  representativeEmail?: string
  representativePhone?: string
  
  creditAgency?: string
  creditRating?: string
  cashFlowRating?: string
  corporateRegistrationNumber?: string
  businessSize?: string

  country?: string
  status?: "PENDING_REVIEW" | "IN_REVIEW" | "IN_PQ" | "PQ_FAILED" | "APPROVED" | "ACTIVE" | "INACTIVE" | "BLACKLISTED" | "PQ_SUBMITTED"
}

// Updated createVendor function with taxId duplicate check
export async function createVendor(params: {
  vendorData: CreateVendorData
  // 기존의 일반 첨부파일
  files?: File[]
  
  // 신용평가 / 현금흐름 등급 첨부
  creditRatingFiles?: File[]
  cashFlowRatingFiles?: File[]
  contacts: {
    contactName: string
    contactPosition?: string
    contactEmail: string
    contactPhone?: string
    isPrimary?: boolean
  }[]
}) {
  unstable_noStore() // Next.js 서버 액션 캐싱 방지
  
  try {
    const { vendorData, files = [], creditRatingFiles = [], cashFlowRatingFiles = [], contacts } = params
    
    // 이메일 중복 검사 - 이미 users 테이블에 존재하는지 확인
    const existingUser = await db
      .select({ id: users.id })
      .from(users)
      .where(eq(users.email, vendorData.email))
      .limit(1);
    
    // 이미 사용자가 존재하면 에러 반환
    if (existingUser.length > 0) {
      return {
        data: null,
        error: `이미 등록된 이메일입니다. 다른 이메일을 사용해주세요. (Email ${vendorData.email} already exists in the system)`
      };
    }
    
    // taxId 중복 검사 추가
    const existingVendor = await db
      .select({ id: vendors.id })
      .from(vendors)
      .where(eq(vendors.taxId, vendorData.taxId))
      .limit(1);
    
    // 이미 동일한 taxId를 가진 업체가 존재하면 에러 반환
    if (existingVendor.length > 0) {
      return {
        data: null,
        error: `이미 등록된 사업자등록번호입니다. (Tax ID ${vendorData.taxId} already exists in the system)`
      };
    }
    
    await db.transaction(async (tx) => {
      // 1) Insert the vendor (확장 필드도 함께)
      const [newVendor] = await insertVendor(tx, {
        vendorName: vendorData.vendorName,
        vendorCode: vendorData.vendorCode || null,
        address: vendorData.address || null,
        country: vendorData.country || null,
        phone: vendorData.phone || null,
        email: vendorData.email,
        website: vendorData.website || null,
        status: vendorData.status ?? "PENDING_REVIEW",
        taxId: vendorData.taxId,
        vendorTypeId: vendorData.vendorTypeId,
        items: vendorData.items || null,
        
        // 대표자 정보
        representativeName: vendorData.representativeName || null,
        representativeBirth: vendorData.representativeBirth || null,
        representativeEmail: vendorData.representativeEmail || null,
        representativePhone: vendorData.representativePhone || null,
        corporateRegistrationNumber: vendorData.corporateRegistrationNumber || null,
        
        // 신용/현금흐름
        creditAgency: vendorData.creditAgency || null,
        creditRating: vendorData.creditRating || null,
        cashFlowRating: vendorData.cashFlowRating || null,
      })
      
      // 2) If there are attached files, store them
      // (2-1) 일반 첨부
      if (files.length > 0) {
        await storeVendorFiles(tx, newVendor.id, files, "GENERAL")
      }
      
      // (2-2) 신용평가 파일
      if (creditRatingFiles.length > 0) {
        await storeVendorFiles(tx, newVendor.id, creditRatingFiles, "CREDIT_RATING")
      }
      
      // (2-3) 현금흐름 파일
      if (cashFlowRatingFiles.length > 0) {
        await storeVendorFiles(tx, newVendor.id, cashFlowRatingFiles, "CASH_FLOW_RATING")
      }
      
      for (const contact of contacts) {
        await tx.insert(vendorContacts).values({
          vendorId: newVendor.id,
          contactName: contact.contactName,
          contactPosition: contact.contactPosition || null,
          contactEmail: contact.contactEmail,
          contactPhone: contact.contactPhone || null,
          isPrimary: contact.isPrimary ?? false,
        })
      }
    })
    
    revalidateTag("vendors")
    return { data: null, error: null }
  } catch (error) {
    return { data: null, error: getErrorMessage(error) }
  }
}
/* -----------------------------------------------------
   3) 업데이트 (단건/복수)
----------------------------------------------------- */

/** 단건 업데이트 */
export async function modifyVendor(
  input: UpdateVendorSchema & { id: string; userId: number; comment:string; } // userId 추가
) {
  unstable_noStore();
  try {
    const updated = await db.transaction(async (tx) => {
      // 1. 업데이트 전에 기존 벤더 정보를 가져옴
      const existingVendor = await tx.query.vendors.findFirst({
        where: eq(vendors.id, parseInt(input.id)),
        columns: {
          status: true, // 상태 변경 로깅에 필요한 현재 상태만 가져옴
        },
      });

      if (!existingVendor) {
        throw new Error(`Vendor with ID ${input.id} not found`);
      }

      const oldStatus = existingVendor.status;

      // 2. 벤더 정보 업데이트
      const [res] = await updateVendor(tx, input.id, {
        vendorName: input.vendorName,
        vendorCode: input.vendorCode,
        address: input.address,
        country: input.country,
        phone: input.phone,
        email: input.email,
        website: input.website,
        creditAgency: input.creditAgency,
        creditRating: input.creditRating,
        cashFlowRating: input.cashFlowRating,
        status: input.status,
      });

      // 3. 상태가 변경되었다면 로그 기록
      if (oldStatus !== input.status) {
        await tx.insert(vendorsLogs).values({
          vendorId: parseInt(input.id),
          userId: input.userId,
          action: "status_change",
          oldStatus,
          newStatus: input.status,
          comment: input.comment || `Status changed from ${oldStatus} to ${input.status}`,
        });
      } else if (input.comment) {
        // 상태 변경이 없더라도 코멘트가 있으면 로그 기록
        await tx.insert(vendorsLogs).values({
          vendorId: parseInt(input.id),
          userId: input.userId,
          action: "vendor_updated",
          comment: input.comment,
        });
      }

      return res;
    });

    // 필요 시, status 변경 등에 따른 다른 캐시도 무효화
    revalidateTag("vendors");
    revalidateTag("rfq-vendors");

    return { data: updated, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}

/** 복수 업데이트 */
export async function modifyVendors(input: {
  ids: string[];
  status?: Vendor["status"];
}) {
  unstable_noStore();
  try {
    const data = await db.transaction(async (tx) => {
      // 여러 협력업체 일괄 업데이트
      const [updated] = await updateVendors(tx, input.ids, {
        // 예: 상태만 일괄 변경
        status: input.status,
      });
      return updated;
    });

    revalidateTag("vendors");
    if (data.status === input.status) {
      revalidateTag("vendor-status-counts");
    }
    return { data: null, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}

export const findVendorById = async (id: number): Promise<Vendor | null> => {
  try {
    logger.info({ id }, 'Fetching user by ID');
    const vendor = await getVendorById(id);
    if (!vendor) {
      logger.warn({ id }, 'User not found');
    } else {
      logger.debug({ vendor }, 'User fetched successfully');
    }
    return vendor;
  } catch (error) {
    logger.error({ error }, 'Error fetching user by ID');
    throw new Error('Failed to fetch user');
  }
};


export const findVendorContactsById = async (id: number): Promise<VendorContact | null> => {
  try {
    logger.info({ id }, 'Fetching user by ID');
    const vendor = await getVendorContactsById(id);
    if (!vendor) {
      logger.warn({ id }, 'User not found');
    } else {
      logger.debug({ vendor }, 'User fetched successfully');
    }
    return vendor;
  } catch (error) {
    logger.error({ error }, 'Error fetching user by ID');
    throw new Error('Failed to fetch user');
  }
};


export async function getVendorContacts(input: GetVendorContactsSchema, id: number) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // const advancedTable = input.flags.includes("advancedTable");
        const advancedTable = true;


        // advancedTable 모드면 filterColumns()로 where 절 구성
        const advancedWhere = filterColumns({
          table: vendorContacts,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });


        let globalWhere
        if (input.search) {
          const s = `%${input.search}%`
          globalWhere = or(ilike(vendorContacts.contactName, s), ilike(vendorContacts.contactPosition, s)
            , ilike(vendorContacts.contactEmail, s), ilike(vendorContacts.contactPhone, s)
          )
          // 필요시 여러 칼럼 OR조건 (status, priority, etc)
        }

        const vendorWhere = eq(vendorContacts.vendorId, id)

        const finalWhere = and(
          // advancedWhere or your existing conditions
          advancedWhere,
          globalWhere,
          vendorWhere
        )


        // 아니면 ilike, inArray, gte 등으로 where 절 구성
        const where = finalWhere

        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(vendorContacts[item.id]) : asc(vendorContacts[item.id])
            )
            : [asc(vendorContacts.createdAt)];

        // 트랜잭션 내부에서 Repository 호출
        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectVendorContacts(tx, {
            where,
            orderBy,
            offset,
            limit: input.perPage,
          });
          const total = await countVendorContacts(tx, where);
          return { data, total };
        });



        const pageCount = Math.ceil(total / input.perPage);


        return { data, pageCount };
      } catch (err) {
        // 에러 발생 시 디폴트
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input), String(id)], // 캐싱 키
    {
      revalidate: 3600,
      tags: [`vendor-contacts-${id}`], // revalidateTag("tasks") 호출 시 무효화
    }
  )();
}

export async function createVendorContact(input: CreateVendorContactSchema) {
  unstable_noStore(); // Next.js 서버 액션 캐싱 방지
  try {
    await db.transaction(async (tx) => {
      // DB Insert
      const [newContact] = await insertVendorContact(tx, {
        vendorId: input.vendorId,
        contactName: input.contactName,
        contactPosition: input.contactPosition || "",
        contactEmail: input.contactEmail,
        contactPhone: input.contactPhone || "",
        isPrimary: input.isPrimary || false,
      });
      return newContact;
    });

    // 캐시 무효화 (협력업체 연락처 목록 등)
    revalidateTag(`vendor-contacts-${input.vendorId}`);

    return { data: null, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}


///item

export async function getVendorItems(input: GetVendorItemsSchema, id: number) {
  const cachedFunction = unstable_cache(

    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // const advancedTable = input.flags.includes("advancedTable");
        const advancedTable = true;

        // advancedTable 모드면 filterColumns()로 where 절 구성
        const advancedWhere = filterColumns({
          table: vendorItemsView,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });


        let globalWhere
        if (input.search) {
          const s = `%${input.search}%`
          globalWhere = or(ilike(vendorItemsView.itemCode, s)
            , ilike(vendorItemsView.description, s)
          )
          // 필요시 여러 칼럼 OR조건 (status, priority, etc)
        }

        const vendorWhere = eq(vendorItemsView.vendorId, id)

        const finalWhere = and(
          // advancedWhere or your existing conditions
          advancedWhere,
          globalWhere,
          vendorWhere
        )


        // 아니면 ilike, inArray, gte 등으로 where 절 구성
        const where = finalWhere

        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(vendorItemsView[item.id]) : asc(vendorItemsView[item.id])
            )
            : [asc(vendorItemsView.createdAt)];

        // 트랜잭션 내부에서 Repository 호출
        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectVendorItems(tx, {
            where,
            orderBy,
            offset,
            limit: input.perPage,
          });
          const total = await countVendorItems(tx, where);
          return { data, total };
        });


        const pageCount = Math.ceil(total / input.perPage);


        console.log(data)

        return { data, pageCount };
      } catch (err) {
        // 에러 발생 시 디폴트
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input), String(id)], // 캐싱 키
    {
      revalidate: 3600,
      tags: [`vendor-items-${id}`], // revalidateTag("tasks") 호출 시 무효화
    }
  );
  return cachedFunction();
}

export async function getVendorMaterials(input: GetVendorMaterialsSchema, id: number) {
  const cachedFunction = unstable_cache(

    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // const advancedTable = input.flags.includes("advancedTable");
        const advancedTable = true;

        // advancedTable 모드면 filterColumns()로 where 절 구성
        const advancedWhere = filterColumns({
          table: vendorMaterialsView,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });


        let globalWhere
        if (input.search) {
          const s = `%${input.search}%`
          globalWhere = or(ilike(vendorMaterialsView.itemCode, s)
            , ilike(vendorMaterialsView.description, s)
          )
          // 필요시 여러 칼럼 OR조건 (status, priority, etc)
        }

        const vendorWhere = eq(vendorMaterialsView.vendorId, id)

        const finalWhere = and(
          // advancedWhere or your existing conditions
          advancedWhere,
          globalWhere,
          vendorWhere
        )


        // 아니면 ilike, inArray, gte 등으로 where 절 구성
        const where = finalWhere

        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(vendorMaterialsView[item.id]) : asc(vendorMaterialsView[item.id])
            )
            : [asc(vendorMaterialsView.createdAt)];

        // 트랜잭션 내부에서 Repository 호출
        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectVendorMaterials(tx, {
            where,
            orderBy,
            offset,
            limit: input.perPage,
          });
          const total = await countVendorMaterials(tx, where);
          return { data, total };
        });


        const pageCount = Math.ceil(total / input.perPage);


        console.log(data)

        return { data, pageCount };
      } catch (err) {
        // 에러 발생 시 디폴트
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input), String(id)], // 캐싱 키
    {
      revalidate: 3600,
      tags: [`vendor-materials-${id}`], // revalidateTag("tasks") 호출 시 무효화
    }
  );
  return cachedFunction();
}

export interface ItemDropdownOption {
  itemCode: string;
  itemName: string;
  description: string | null;
}

/**
 * Vendor Item 추가 시 사용할 아이템 목록 조회 (전체 목록 반환)
 * 아이템 코드, 이름, 설명만 간소화해서 반환
 */
export async function getItemsForVendor(vendorId: number) {
  return unstable_cache(
    async () => {
      try {
        // 해당 vendorId가 이미 가지고 있는 itemCode 목록을 서브쿼리로 구함
        // 그 아이템코드를 제외(notIn)하여 모든 items 테이블에서 조회
        const itemsData = await db
          .select({
            itemCode: items.itemCode,
            itemName: items.itemName,
            description: items.description,
          })
          .from(items)
          .leftJoin(
            vendorPossibleItems,
            eq(items.itemCode, vendorPossibleItems.itemCode)
          )
          // vendorPossibleItems.vendorId가 이 vendorId인 행이 없는(즉 아직 등록되지 않은) 아이템만
          .where(
            isNull(vendorPossibleItems.id) // 또는 isNull(vendorPossibleItems.itemCode)
          )
          .orderBy(asc(items.itemName))

        return {
          data: itemsData.map((item) => ({
            itemCode: item.itemCode ?? "",     // null이라면 ""로 치환
            itemName: item.itemName,
            description: item.description ?? ""  // null이라면 ""로 치환
          })),
          error: null
        }
      } catch (err) {
        console.error("Failed to fetch items for vendor dropdown:", err)
        return {
          data: [],
          error: "아이템 목록을 불러오는데 실패했습니다.",
        }
      }
    },
    // 캐시 키를 vendorId 별로 달리 해야 한다.
    ["items-for-vendor", String(vendorId)],
    {
      revalidate: 3600, // 1시간 캐싱
      tags: ["items"],   // revalidateTag("items") 호출 시 무효화
    }
  )()
}

export async function createVendorItem(input: CreateVendorItemSchema) {
  unstable_noStore(); // Next.js 서버 액션 캐싱 방지
  try {
    await db.transaction(async (tx) => {
      // DB Insert
      const [newContact] = await insertVendorItem(tx, {
        vendorId: input.vendorId,
        itemCode: input.itemCode,

      });
      return newContact;
    });

    // 캐시 무효화 (협력업체 연락처 목록 등)
    revalidateTag(`vendor-items-${input.vendorId}`);

    return { data: null, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}



const updateVendorItemSchema = z.object({
  oldItemCode: z.string().min(1, "Old item code is required"),
  newItemCode: z.string().min(1, "New item code is required"),
  vendorId: z.number().min(1, "Vendor ID is required"),
})


export async function deleteVendorItem(
  vendorId: number,
  itemCode: string
) {
  try {
    const validatedData = deleteVendorItemSchema.parse({
      itemCode,
      vendorId,
    })

    await db
      .delete(vendorPossibleItems)
      .where(
        and(
          eq(vendorPossibleItems.itemCode, validatedData.itemCode),
          eq(vendorPossibleItems.vendorId, validatedData.vendorId)
        )
      )

      revalidateTag(`vendor-items-${vendorId}`);
      
    return { success: true, message: "Item deleted successfully" }
  } catch (error) {
    console.error("Error deleting vendor item:", error)
    return { 
      success: false, 
      message: error instanceof z.ZodError 
        ? error.errors[0].message 
        : "Failed to delete item" 
    }
  }
}

export async function updateVendorItem(
  vendorId: number,
  oldItemCode: string,
  newItemCode: string
) {
  unstable_noStore(); // Next.js 서버 액션 캐싱 방지
  
  try {
    const validatedData = updateVendorItemSchema.parse({
      oldItemCode,
      newItemCode,
      vendorId,
    })

    await db.transaction(async (tx) => {
      // 기존 아이템 삭제
      await tx
        .delete(vendorPossibleItems)
        .where(
          and(
            eq(vendorPossibleItems.itemCode, validatedData.oldItemCode),
            eq(vendorPossibleItems.vendorId, validatedData.vendorId)
          )
        )

      // 새 아이템 추가
      await tx.insert(vendorPossibleItems).values({
        vendorId: validatedData.vendorId,
        itemCode: validatedData.newItemCode,
      })
    })

    // 캐시 무효화
    revalidateTag(`vendor-items-${vendorId}`)
    
    return { data: null, error: null }
  } catch (err) {
    console.error("Error updating vendor item:", err)
    return { 
      data: null, 
      error: getErrorMessage(err)
    }
  }
}

export async function removeVendorItems(input: {
  itemCodes: string[]
  vendorId: number
}) {
  unstable_noStore()
  
  try {
    const validatedData = removeVendorItemsSchema.parse(input)

    await db
      .delete(vendorPossibleItems)
      .where(
        and(
          inArray(vendorPossibleItems.itemCode, validatedData.itemCodes),
          eq(vendorPossibleItems.vendorId, validatedData.vendorId)
        )
      )

    revalidateTag(`vendor-items-${validatedData.vendorId}`)
    
    return { data: null, error: null }
  } catch (err) {
    console.error("Error deleting vendor items:", err)
    return { 
      data: null, 
      error: getErrorMessage(err)
    }
  }
}

// 스키마도 추가해야 합니다
const removeVendorItemsSchema = z.object({
  itemCodes: z.array(z.string()).min(1, "At least one item code is required"),
  vendorId: z.number().min(1, "Vendor ID is required"),
})

const deleteVendorItemSchema = z.object({
  itemCode: z.string().min(1, "Item code is required"),
  vendorId: z.number().min(1, "Vendor ID is required"),
})

export async function getMaterialsForVendor(vendorId: number) {
  return unstable_cache(
    async () => {
      try {
        // 해당 vendorId가 이미 가지고 있는 itemCode 목록을 서브쿼리로 구함
        // 그 아이템코드를 제외(notIn)하여 모든 items 테이블에서 조회
        const itemsData = await db
          .select({
            itemCode: materials.itemCode,
            itemName: materials.itemName,
            description: materials.description,
          })
          .from(materials)
          .leftJoin(
            vendorPossibleMateirals,
            eq(materials.itemCode, vendorPossibleMateirals.itemCode)
          )
          // vendorPossibleItems.vendorId가 이 vendorId인 행이 없는(즉 아직 등록되지 않은) 아이템만
          .where(
            isNull(vendorPossibleMateirals.id) // 또는 isNull(vendorPossibleItems.itemCode)
          )
          .orderBy(asc(materials.itemName))

        return {
          data: itemsData.map((item) => ({
            itemCode: item.itemCode ?? "",     // null이라면 ""로 치환
            itemName: item.itemName,
            description: item.description ?? ""  // null이라면 ""로 치환
          })),
          error: null
        }
      } catch (err) {
        console.error("Failed to fetch items for vendor dropdown:", err)
        return {
          data: [],
          error: "아이템 목록을 불러오는데 실패했습니다.",
        }
      }
    },
    // 캐시 키를 vendorId 별로 달리 해야 한다.
    ["materials-for-vendor", String(vendorId)],
    {
      revalidate: 3600, // 1시간 캐싱
      tags: ["materials"],   // revalidateTag("materials") 호출 시 무효화
    }
  )()
}

export async function createVendorMaterial(input: CreateVendorItemSchema) {
  unstable_noStore(); // Next.js 서버 액션 캐싱 방지
  try {
    await db.transaction(async (tx) => {
      // DB Insert
      const [newContact] = await insertVendorMaterial(tx, {
        vendorId: input.vendorId,
        itemCode: input.itemCode,

      });
      return newContact;
    });

    // 캐시 무효화 (협력업체 연락처 목록 등)
    revalidateTag(`vendor-materials-${input.vendorId}`);

    return { data: null, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}

const updateVendorMaterialSchema = z.object({
  oldItemCode: z.string().min(1, "Old item code is required"),
  newItemCode: z.string().min(1, "New item code is required"),
  vendorId: z.number().min(1, "Vendor ID is required"),
})


export async function deleteVendorMaterial(
  vendorId: number,
  itemCode: string
) {
  try {
    const validatedData = deleteVendorItemSchema.parse({
      itemCode,
      vendorId,
    })

    await db
      .delete(vendorPossibleMateirals)
      .where(
        and(
          eq(vendorPossibleMateirals.itemCode, validatedData.itemCode),
          eq(vendorPossibleMateirals.vendorId, validatedData.vendorId)
        )
      )

      revalidateTag(`vendor-materials-${vendorId}`);
      
    return { success: true, message: "Item deleted successfully" }
  } catch (error) {
    console.error("Error deleting vendor item:", error)
    return { 
      success: false, 
      message: error instanceof z.ZodError 
        ? error.errors[0].message 
        : "Failed to delete item" 
    }
  }
}

export async function updateVendorMaterial(
  vendorId: number,
  oldItemCode: string,
  newItemCode: string
) {
  unstable_noStore(); // Next.js 서버 액션 캐싱 방지
  
  try {
    const validatedData = updateVendorMaterialSchema.parse({
      oldItemCode,
      newItemCode,
      vendorId,
    })

    await db.transaction(async (tx) => {
      // 기존 아이템 삭제
      await tx
        .delete(vendorPossibleMateirals)
        .where(
          and(
            eq(vendorPossibleMateirals.itemCode, validatedData.oldItemCode),
            eq(vendorPossibleMateirals.vendorId, validatedData.vendorId)
          )
        )

      // 새 아이템 추가
      await tx.insert(vendorPossibleMateirals).values({
        vendorId: validatedData.vendorId,
        itemCode: validatedData.newItemCode,
      })
    })

    // 캐시 무효화
    revalidateTag(`vendor-items-${vendorId}`)
    
    return { data: null, error: null }
  } catch (err) {
    console.error("Error updating vendor item:", err)
    return { 
      data: null, 
      error: getErrorMessage(err)
    }
  }
}

export async function removeVendorMaterials(input: {
  itemCodes: string[]
  vendorId: number
}) {
  unstable_noStore()
  
  try {
    const validatedData = removeVendormaterialsSchema.parse(input)

    await db
      .delete(vendorPossibleMateirals)
      .where(
        and(
          inArray(vendorPossibleMateirals.itemCode, validatedData.itemCodes),
          eq(vendorPossibleMateirals.vendorId, validatedData.vendorId)
        )
      )

    revalidateTag(`vendor-materials-${validatedData.vendorId}`)
    
    return { data: null, error: null }
  } catch (err) {
    console.error("Error deleting vendor items:", err)
    return { 
      data: null, 
      error: getErrorMessage(err)
    }
  }
}

// 스키마도 추가해야 합니다
const removeVendormaterialsSchema = z.object({
  itemCodes: z.array(z.string()).min(1, "At least one item code is required"),
  vendorId: z.number().min(1, "Vendor ID is required"),
})



export async function getRfqHistory(input: GetRfqHistorySchema, vendorId: number) {
  return unstable_cache(
    async () => {
      try {
        logger.info({ vendorId, input }, "Starting getRfqHistory");

        const offset = (input.page - 1) * input.perPage;

        // 기본 where 조건 (vendorId)
        const vendorWhere = eq(vendorRfqView.vendorId, vendorId);
        logger.debug({ vendorWhere }, "Vendor where condition");

        // 고급 필터링
        const advancedWhere = filterColumns({
          table: vendorRfqView,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });
        logger.debug({ advancedWhere }, "Advanced where condition");

        // 글로벌 검색
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(vendorRfqView.rfqCode, s),
            ilike(vendorRfqView.projectCode, s),
            ilike(vendorRfqView.projectName, s)
          );
          logger.debug({ globalWhere, search: input.search }, "Global search condition");
        }

        const finalWhere = and(
          advancedWhere,
          globalWhere,
          vendorWhere
        );
        logger.debug({ finalWhere }, "Final where condition");

        // 정렬 조건
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(rfqs[item.id]) : asc(rfqs[item.id])
            )
            : [desc(rfqs.createdAt)];
        logger.debug({ orderBy }, "Order by condition");

        // 트랜잭션으로 데이터 조회
        const { data, total } = await db.transaction(async (tx) => {
          logger.debug("Starting transaction for RFQ history query");

          const data = await selectRfqHistory(tx, {
            where: finalWhere,
            orderBy,
            offset,
            limit: input.perPage,
          });
          logger.debug({ dataLength: data.length }, "RFQ history data fetched");

          // RFQ 아이템 정보 조회
          const rfqIds = data.map(rfq => rfq.id);
          const items = await tx
            .select({
              rfqId: rfqItems.rfqId,
              id: rfqItems.id,
              itemCode: rfqItems.itemCode,
              description: rfqItems.description,
              quantity: rfqItems.quantity,
              uom: rfqItems.uom,
            })
            .from(rfqItems)
            .where(inArray(rfqItems.rfqId, rfqIds));

          // RFQ 데이터에 아이템 정보 추가
          const dataWithItems = data.map(rfq => ({
            ...rfq,
            items: items.filter(item => item.rfqId === rfq.id),
          }));

          const total = await countRfqHistory(tx, finalWhere);
          logger.debug({ total }, "RFQ history total count");

          return { data: dataWithItems, total };
        });

        const pageCount = Math.ceil(total / input.perPage);
        logger.info({
          vendorId,
          dataLength: data.length,
          total,
          pageCount
        }, "RFQ history query completed");

        return { data, pageCount };
      } catch (err) {
        logger.error({
          err,
          vendorId,
          stack: err instanceof Error ? err.stack : undefined
        }, 'Error fetching RFQ history');
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify({ input, vendorId })],
    {
      revalidate: 3600,
      tags: ["rfq-history"],
    }
  )();
}

export async function checkJoinPortal(taxID: string) {
  try {
    // 이미 등록된 회사가 있는지 검색
    const result = await db.query.vendors.findFirst({
      where: eq(vendors.taxId, taxID)
    });

    if (result) {
      // 이미 가입되어 있음
      return {
        success: false,
        data: result.vendorName ?? "Already joined",
      }
    }

    // 미가입 → 가입 가능
    return {
      success: true,
    }
  } catch (err) {
    console.error("checkJoinPortal error:", err)
    // 서버 에러 시
    return {
      success: false,
      data: "서버 에러가 발생했습니다.",
    }
  }
}

interface CreateCompanyInput {
  vendorName: string
  taxId: string
  email: string
  address: string
  phone?: string
  country?: string
  // 필요한 필드 추가 가능 (vendorCode, website 등)
}


/**
 * 협력업체 첨부파일 다운로드를 위한 서버 액션
 * @param vendorId 협력업체 ID
 * @param fileId 특정 파일 ID (단일 파일 다운로드시)
 * @returns 다운로드할 수 있는 임시 URL
 */
export async function downloadVendorAttachments(vendorId:number, fileId?:number) {
  try {
    // API 경로 생성 (단일 파일 또는 모든 파일)
    const url = fileId
      ? `/api/vendors/attachments/download?id=${fileId}&vendorId=${vendorId}`
      : `/api/vendors/attachments/download-all?vendorId=${vendorId}`;
    
    // fetch 요청 (기본적으로 Blob으로 응답 받기)
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    if (!response.ok) {
      throw new Error(`Server responded with ${response.status}: ${response.statusText}`);
    }
    
    // 파일명 가져오기 (Content-Disposition 헤더에서)
    const contentDisposition = response.headers.get('content-disposition');
    let fileName = fileId ? `file-${fileId}.zip` : `vendor-${vendorId}-files.zip`;
    
    if (contentDisposition) {
      const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
      if (matches && matches[1]) {
        fileName = matches[1].replace(/['"]/g, '');
      }
    }
    
    // Blob으로 응답 변환
    const blob = await response.blob();
    
    // Blob URL 생성
    const blobUrl = window.URL.createObjectURL(blob);
    
    return { 
      url: blobUrl,
      fileName,
      blob
    };
  } catch (error) {
    console.error('Download API error:', error);
    throw error;
  }
}

/**
 * 임시 ZIP 파일 정리를 위한 서버 액션
 * @param fileName 정리할 파일명
 */
export async function cleanupTempFiles(fileName: string) {
  'use server';

  try {

    await deleteFile(`tmp/${fileName}`)

    return { success: true };
  } catch (error) {
    console.error('임시 파일 정리 오류:', error);
    return { success: false, error: '임시 파일 정리 중 오류가 발생했습니다.' };
  }
}


interface ApproveVendorsInput {
  ids: number[];
  projectId?: number | null
}

/**
 * 선택된 벤더의 상태를 IN_REVIEW로 변경하고 이메일 알림을 발송하는 서버 액션
 */
export async function approveVendors(input: ApproveVendorsInput & { userId: number }) {
  unstable_noStore();
  
  try {
    // 트랜잭션 내에서 협력업체 상태 업데이트, 유저 생성 및 이메일 발송
    const result = await db.transaction(async (tx) => {
      // 0. 업데이트 전 협력업체 상태 조회
      const vendorsBeforeUpdate = await tx
        .select({
          id: vendors.id,
          status: vendors.status,
        })
        .from(vendors)
        .where(inArray(vendors.id, input.ids));

      // 1. 협력업체 상태 업데이트
      const [updated] = await tx
        .update(vendors)
        .set({
          status: "IN_REVIEW",
          updatedAt: new Date()
        })
        .where(inArray(vendors.id, input.ids))
        .returning();

      // 2. 업데이트된 협력업체 정보 조회
      const updatedVendors = await tx
        .select({
          id: vendors.id,
          vendorName: vendors.vendorName,
          email: vendors.email,
        })
        .from(vendors)
        .where(inArray(vendors.id, input.ids));

      // 3. 각 벤더에 대한 유저 계정 생성
      await Promise.all(
        updatedVendors.map(async (vendor) => {
          if (!vendor.email) return; // 이메일이 없으면 스킵

          // 이미 존재하는 유저인지 확인
          const existingUser = await tx.query.users.findFirst({
            where: eq(users.email, vendor.email),
            columns: {
              id: true
            }
          });

          // 유저가 존재하지 않는 경우에만 생성
          if (!existingUser) {
            // 유저 생성
            const [newUser] = await tx.insert(users).values({
              name: vendor.vendorName,
              email: vendor.email,
              companyId: vendor.id,
              domain: "partners", // 기본값으로 이미 설정되어 있지만 명시적으로 지정
            }).returning({ id: users.id });

            // "Vendor Admin" 역할 찾기 또는 생성
            let vendorAdminRole = await tx.query.roles.findFirst({
              where: and(
                eq(roles.name, "Vendor Admin"),
                eq(roles.domain, "partners"),
                eq(roles.companyId, vendor.id)
              ),
              columns: {
                id: true
              }
            });

            // "Vendor Admin" 역할이 없다면 생성
            if (!vendorAdminRole) {
              const [newRole] = await tx.insert(roles).values({
                name: "Vendor Admin",
                domain: "partners",
                companyId: vendor.id,
                description: "Vendor Administrator role",
              }).returning({ id: roles.id });
              
              vendorAdminRole = newRole;
            }

            // userRoles 테이블에 관계 생성
            await tx.insert(userRoles).values({
              userId: newUser.id,
              roleId: vendorAdminRole.id,
            });
          }
        })
      );

      // 4. 로그 기록
      await Promise.all(
        vendorsBeforeUpdate.map(async (vendorBefore) => {
          await tx.insert(vendorsLogs).values({
            vendorId: vendorBefore.id,
            userId: input.userId,
            action: "status_change",
            oldStatus: vendorBefore.status,
            newStatus: "IN_REVIEW",
            comment: "Vendor approved for review",
          });
        })
      );

      // 5. 각 벤더에게 이메일 발송
      await Promise.all(
        updatedVendors.map(async (vendor) => {
          if (!vendor.email) return; // 이메일이 없으면 스킵

          try {
            const userLang = "en"; // 기본값, 필요시 협력업체 언어 설정에서 가져오기

            const subject =
              "[eVCP] Admin Account Created";

            const headersList = await headers();
            const host = headersList.get('host') || 'localhost:3000';
            const baseUrl = `http://${host}`
            const loginUrl = `${baseUrl}/en/login`;

            await sendEmail({
              to: vendor.email,
              subject,
              template: "admin-created", // 이메일 템플릿 이름
              context: {
                vendorName: vendor.vendorName,
                loginUrl,
                language: userLang,
              },
            });
          } catch (emailError) {
            console.error(`Failed to send email to vendor ${vendor.id}:`, emailError);
            // 이메일 전송 실패는 전체 트랜잭션을 실패시키지 않음
          }
        })
      );

      return updated;
    });

    // 캐시 무효화
    revalidateTag("vendors");
    revalidateTag("vendor-status-counts");
    revalidateTag("users"); // 유저 캐시도 무효화
    revalidateTag("roles"); // 역할 캐시도 무효화
    revalidateTag("user-roles"); // 유저 역할 캐시도 무효화

    return { data: result, error: null };
  } catch (err) {
    console.error("Error approving vendors:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 유니크한 PQ 번호 생성 함수
 * 
 * 형식: PQ-YYMMDD-XXXXX
 * YYMMDD: 연도(YY), 월(MM), 일(DD)
 * XXXXX: 시퀀스 번호 (00001부터 시작)
 * 
 * 예: PQ-240520-00001, PQ-240520-00002, ...
 */
export async function generatePQNumber(isProject: boolean = false) {
  try {
    // 현재 날짜 가져오기
    const now = new Date();
    const year = now.getFullYear().toString().slice(-2); // 년도의 마지막 2자리
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 월 (01-12)
    const day = now.getDate().toString().padStart(2, '0'); // 일 (01-31)
    const dateStr = `${year}${month}${day}`;
    
    // 접두사 설정 (일반 PQ vs 프로젝트 PQ)
    const prefix = isProject ? "PPQ" : "PQ";
    const datePrefix = `${prefix}-${dateStr}`;
    
    // 오늘 생성된 가장 큰 시퀀스 번호 조회
    const latestPQ = await db
      .select({ pqNumber: vendorPQSubmissions.pqNumber })
      .from(vendorPQSubmissions)
      .where(
        sql`${vendorPQSubmissions.pqNumber} LIKE ${datePrefix + '-%'}`
      )
      .orderBy(desc(vendorPQSubmissions.pqNumber))
      .limit(1);
    
    let sequenceNumber = 1; // 기본값은 1
    
    // 오늘 생성된 PQ가 있으면 다음 시퀀스 번호 계산
    if (latestPQ.length > 0 && latestPQ[0].pqNumber) {
      const lastPQ = latestPQ[0].pqNumber;
      const lastSequence = lastPQ.split('-')[2];
      if (lastSequence && !isNaN(parseInt(lastSequence))) {
        sequenceNumber = parseInt(lastSequence) + 1;
      }
    }
    
    // 5자리 시퀀스 번호로 포맷팅 (00001, 00002, ...)
    const formattedSequence = sequenceNumber.toString().padStart(5, '0');
    
    // 최종 PQ 번호 생성
    const pqNumber = `${datePrefix}-${formattedSequence}`;
    
    return pqNumber;
  } catch (error) {
    console.error('Error generating PQ number:', error);
    // 문제 발생 시 대체 번호 생성 (타임스탬프 기반)
    const timestamp = Date.now().toString();
    const prefix = isProject ? "PPQ" : "PQ";
    return `${prefix}-${timestamp}`;
  }
}

export async function requestPQVendors(input: ApproveVendorsInput & { 
  userId: number, 
  agreements?: Record<string, boolean>, 
  dueDate?: string | null,
  type?: "GENERAL" | "PROJECT" | "NON_INSPECTION",
  extraNote?: string,
  pqItems?: string
}) {
  unstable_noStore();

  const session = await getServerSession(authOptions);
  const requesterId = session?.user?.id ? Number(session.user.id) : null;

  try {
    let projectInfo = null;
    if (input.projectId) {
      const project = await db
        .select({
          id: projects.id,
          projectCode: projects.code,
          projectName: projects.name,
        })
        .from(projects)
        .where(eq(projects.id, input.projectId))
        .limit(1);

      if (project.length > 0) {
        projectInfo = project[0];
      }
    }

    const result = await db.transaction(async (tx) => {
      const vendorsBeforeUpdate = await tx
        .select({ id: vendors.id, status: vendors.status })
        .from(vendors)
        .where(inArray(vendors.id, input.ids));

      const [updated] = await tx
        .update(vendors)
        .set({ status: "IN_PQ", updatedAt: new Date() })
        .where(inArray(vendors.id, input.ids))
        .returning();

      const updatedVendors = await tx
        .select({ id: vendors.id, vendorName: vendors.vendorName, email: vendors.email })
        .from(vendors)
        .where(inArray(vendors.id, input.ids));

      const pqType = input.type;
      const currentDate = new Date();

      const existingSubmissions = await tx
        .select({ vendorId: vendorPQSubmissions.vendorId })
        .from(vendorPQSubmissions)
        .where(
          and(
            inArray(vendorPQSubmissions.vendorId, input.ids),
            pqType ? eq(vendorPQSubmissions.type, pqType) : undefined,
            input.projectId
              ? eq(vendorPQSubmissions.projectId, input.projectId)
              : isNull(vendorPQSubmissions.projectId)
          )
        );

      const existingVendorIds = new Set(existingSubmissions.map((s) => s.vendorId));
      const newVendorIds = input.ids.filter((id) => !existingVendorIds.has(id));

      if (newVendorIds.length > 0) {
        const vendorPQDataPromises = newVendorIds.map(async (vendorId) => {
          const pqNumber = await generatePQNumber(pqType === "PROJECT");

                      return {
              vendorId,
              pqNumber,
              projectId: input.projectId || null,
              type: pqType,
              status: "REQUESTED",
              requesterId: input.userId || requesterId,
              dueDate: input.dueDate ? new Date(input.dueDate) : null,
              agreements: input.agreements ?? {},
              pqItems: input.pqItems || null,
              createdAt: currentDate,
              updatedAt: currentDate,
            };
        });

        const vendorPQData = await Promise.all(vendorPQDataPromises);

        await tx.insert(vendorPQSubmissions).values(vendorPQData);
      }

      await Promise.all(
        vendorsBeforeUpdate.map(async (vendorBefore) => {
          await tx.insert(vendorsLogs).values({
            vendorId: vendorBefore.id,
            userId: input.userId,
            action: "status_change",
            oldStatus: vendorBefore.status,
            newStatus: "IN_PQ",
            comment: input.projectId
              ? `Project PQ requested (Project: ${projectInfo?.projectCode || input.projectId})`
              : "General PQ requested",
          });
        })
      );

      const headersList = await headers();
      const host = headersList.get("host") || "localhost:3000";

      await Promise.all(
        updatedVendors.map(async (vendor) => {
          if (!vendor.email) return;

          try {
            const userLang = "en";

            const vendorPQ = await tx
              .select({ pqNumber: vendorPQSubmissions.pqNumber })
              .from(vendorPQSubmissions)
              .where(
                and(
                  eq(vendorPQSubmissions.vendorId, vendor.id),
                  eq(vendorPQSubmissions.type, pqType),
                  input.projectId
                    ? eq(vendorPQSubmissions.projectId, input.projectId)
                    : isNull(vendorPQSubmissions.projectId)
                )
              )
              .limit(1)
              .then((rows) => rows[0]);

            const subject = input.projectId
              ? `[eVCP] You are invited to submit Project PQ ${vendorPQ?.pqNumber || ""} for ${projectInfo?.projectCode || "a project"}`
              : input.type === "NON_INSPECTION"
              ? `[eVCP] You are invited to submit Non-Inspection PQ ${vendorPQ?.pqNumber || ""}`
              : `[eVCP] You are invited to submit PQ ${vendorPQ?.pqNumber || ""}`;

            const baseLoginUrl = `${host}/partners/pq`;
            const loginUrl = input.projectId
              ? `${baseLoginUrl}?projectId=${input.projectId}`
              : baseLoginUrl;

            // 체크된 계약 항목 배열 생성
            const contracts = input.agreements 
              ? Object.entries(input.agreements)
                  .filter(([_, checked]) => checked)
                  .map(([name, _]) => name)
              : [];

            // PQ 대상 품목
            const pqItems = input.pqItems || " - ";

            await sendEmail({
              to: vendor.email,
              subject,
              template: input.projectId ? "project-pq" : input.type === "NON_INSPECTION" ? "non-inspection-pq" : "pq",
              context: {
                vendorName: vendor.vendorName,
                vendorContact: "", // 담당자 정보가 없으므로 빈 문자열
                pqNumber: vendorPQ?.pqNumber || "",
                senderName: session?.user?.name || "eVCP",
                senderEmail: session?.user?.email || "noreply@evcp.com",
                dueDate: input.dueDate ? new Date(input.dueDate).toLocaleDateString('ko-KR') : "",
                pqItems,
                contracts,
                extraNote: input.extraNote || "",
                currentYear: new Date().getFullYear().toString(),
                loginUrl,
                language: userLang,
                projectCode: projectInfo?.projectCode || "",
                projectName: projectInfo?.projectName || "",
                hasProject: !!input.projectId,
                pqType: input.type || "GENERAL",
              },
            });
          } catch (emailError) {
            console.error(`Failed to send email to vendor ${vendor.id}:`, emailError);
          }
        })
      );

      return updated;
    });

    revalidateTag("vendors");
    revalidateTag("vendor-status-counts");
    revalidateTag("vendor-pq-submissions");
    revalidateTag("pq-submissions");
    
    if (input.projectId) {
      revalidateTag(`project-${input.projectId}`);
      revalidateTag(`project-pq-submissions-${input.projectId}`);
    }

    return { data: result, error: null };
  } catch (err) {
    console.error("Error requesting PQ from vendors:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}


interface SendVendorsInput {
  ids: number[];
}

/**
 * APPROVED 상태인 협력업체 정보를 기간계 시스템에 전송하고 협력업체 코드를 업데이트하는 서버 액션
 */
export async function sendVendors(input: SendVendorsInput & { userId: number }) {
  unstable_noStore();

  try {
    // 트랜잭션 내에서 진행
    const result = await db.transaction(async (tx) => {
      // 1. 선택된 협력업체 중 APPROVED 상태인 벤더만 필터링
      const approvedVendors = await db.query.vendors.findMany({
        where: and(
          inArray(vendors.id, input.ids),
          eq(vendors.status, "APPROVED")
        )
      });

      if (!approvedVendors.length) {
        throw new Error("No approved vendors found in the selection");
      }
      // 벤더별 처리 결과를 저장할 배열
      const results = [];

      // 2. 각 벤더에 대해 처리
      for (const vendor of approvedVendors) {
        // 2-1. 협력업체 연락처 정보 조회
        const contacts = await db.query.vendorContacts.findMany({
          where: eq(vendorContacts.vendorId, vendor.id)
        });

        // 2-2. 협력업체 가능 아이템 조회
        const possibleItems = await db.query.vendorPossibleItems.findMany({
          where: eq(vendorPossibleItems.vendorId, vendor.id)
        });
        // 2-3. 협력업체 첨부파일 조회
        const attachments = await db.query.vendorAttachments.findMany({
          where: eq(vendorAttachments.vendorId, vendor.id),
          columns: {
            id: true,
            fileName: true,
            filePath: true
          }
        });

        // 2-4. 협력업체 정보를 기간계 시스템에 전송 (NextJS API 라우트 사용)
        const vendorData = {
          id: vendor.id,
          vendorName: vendor.vendorName,
          taxId: vendor.taxId,
          address: vendor.address || "",
          country: vendor.country || "",
          phone: vendor.phone || "",
          email: vendor.email || "",
          website: vendor.website || "",
          contacts,
          possibleItems,
          attachments,
        };

        try {
          // 내부 API 호출 (기간계 시스템 연동 API)
          const erpResponse = await fetch(`/api/erp/vendors`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(vendorData),
          });

          if (!erpResponse.ok) {
            const errorData = await erpResponse.json();
            throw new Error(`ERP system error for vendor ${vendor.id}: ${errorData.message || erpResponse.statusText}`);
          }

          const responseData = await erpResponse.json();

          if (!responseData.success || !responseData.vendorCode) {
            throw new Error(`Invalid response from ERP system for vendor ${vendor.id}`);
          }

          // 2-5. 협력업체 코드 및 상태 업데이트
          const vendorCode = responseData.vendorCode;

          const [updated] = await tx
            .update(vendors)
            .set({
              vendorCode,
              status: "ACTIVE", // 상태를 ACTIVE로 변경
              updatedAt: new Date(),
            })
            .where(eq(vendors.id, vendor.id))
            .returning();

          // 2-6. 로그 기록
          await tx.insert(vendorsLogs).values({
            vendorId: vendor.id,
            userId: input.userId,
            action: "status_change",
            oldStatus: "APPROVED",
            newStatus: "ACTIVE",
            comment: `Sent to ERP system. Vendor code assigned: ${vendorCode}`,
          });

          const headersList = await headers();
          const host = headersList.get('host') || 'localhost:3000';

          // 2-7. 벤더에게 알림 이메일 발송
          if (vendor.email) {
            const userLang = "en"; // 기본값, 필요시 협력업체 언어 설정에서 가져오기

            const subject =
              "[eVCP] Vendor Registration Completed";

            const portalUrl = `http://${host}/en/partners`;

            await sendEmail({
              to: vendor.email,
              subject,
              template: "vendor-active",
              context: {
                vendorName: vendor.vendorName,
                vendorCode,
                portalUrl,
                language: userLang,
              },
            });
          }

          results.push({
            id: vendor.id,
            success: true,
            vendorCode,
            message: "Successfully sent to ERP system",
          });
        } catch (vendorError) {
          // 개별 협력업체 처리 오류 기록
          results.push({
            id: vendor.id,
            success: false,
            error: getErrorMessage(vendorError),
          });

          // 에러가 발생해도 로그는 기록
          await tx.insert(vendorsLogs).values({
            vendorId: vendor.id,
            userId: input.userId,
            action: "erp_send_failed",
            comment: `Failed to send to ERP: ${getErrorMessage(vendorError)}`,
          });
        }
      }

      // 3. 처리 결과 반환
      const successCount = results.filter(r => r.success).length;
      const failCount = results.filter(r => !r.success).length;

      return {
        totalProcessed: results.length,
        successCount,
        failCount,
        results,
      };
    });

    // 캐시 무효화
    revalidateTag("vendors");
    revalidateTag("vendor-status-counts");

    return { data: result, error: null };
  } catch (err) {
    console.error("Error sending vendors to ERP:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

interface RequestInfoProps {
  ids: number[];
  userId: number; // 추가: 어떤 사용자가 요청했는지 로깅하기 위함
}

export async function requestInfo({ ids, userId }: RequestInfoProps) {
  try {
    return await db.transaction(async (tx) => {
      // 1. 협력업체 정보 가져오기
      const vendorList = await tx.query.vendors.findMany({
        where: inArray(vendors.id, ids),
      });

      if (!vendorList.length) {
        return { error: "협력업체 정보를 찾을 수 없습니다." };
      }

      const headersList = await headers();
      const host = headersList.get('host') || 'localhost:3000';
      
      // 2. 각 벤더에 대한 로그 기록 및 이메일 발송
      for (const vendor of vendorList) {
        // 로그 기록
        await tx.insert(vendorsLogs).values({
          vendorId: vendor.id,
          userId: userId,
          action: "info_requested",
          comment: "추가 정보 요청됨",
        });

        // 이메일이 없는 경우 스킵
        if (!vendor.email) continue;

        // 협력업체 정보 페이지 URL 생성
        const vendorInfoUrl = `http://${host}/partners/info?vendorId=${vendor.id}`;

        // 벤더에게 이메일 보내기
        await sendEmail({
          to: vendor.email,
          subject: "[EVCP] 추가 정보 요청 / Additional Information Request",
          template: "vendor-additional-info",
          context: {
            vendorName: vendor.vendorName,
            vendorInfoUrl: vendorInfoUrl,
            language: "ko", // 기본 언어 설정, 벤더의 선호 언어가 있다면 그것을 사용할 수 있음
          },
        });
      }

      // 3. 성공적으로 처리됨
      return { success: true };
    });
  } catch (error) {
    console.error("협력업체 정보 요청 중 오류 발생:", error);
    return { error: "협력업체 정보 요청 중 오류가 발생했습니다. 다시 시도해 주세요." };
  }
}


export async function getVendorDetailById(id: number) {
  try {
    // View를 통해 협력업체 정보 조회
    const vendor = await db
      .select()
      .from(vendorDetailView)
      .where(eq(vendorDetailView.id, id))
      .limit(1)
      .then(rows => rows[0] || null);

    if (!vendor) {
      return null;
    }

    // JSON 문자열로 반환된 contacts와 attachments를 JavaScript 객체로 파싱
    const contacts = typeof vendor.contacts === 'string'
      ? JSON.parse(vendor.contacts)
      : vendor.contacts;

    const attachments = typeof vendor.attachments === 'string'
      ? JSON.parse(vendor.attachments)
      : vendor.attachments;

    // 파싱된 데이터로 반환
    return {
      ...vendor,
      contacts,
      attachments
    };
  } catch (error) {
    console.error("Error fetching vendor detail:", error);
    throw new Error("Failed to fetch vendor detail");
  }
}

export type UpdateVendorInfoData = {
  id: number
  vendorName: string
  website?: string
  address?: string
  email: string
  phone?: string
  country?: string
  representativeName?: string
  representativeBirth?: string
  representativeEmail?: string
  representativePhone?: string
  corporateRegistrationNumber?: string
  creditAgency?: string
  creditRating?: string
  cashFlowRating?: string
}

export type ContactInfo = {
  id?: number
  contactName: string
  contactPosition?: string
  contactEmail: string
  contactPhone?: string
  isPrimary?: boolean
}

/**
 * 협력업체 정보를 업데이트하는 함수
 */
export async function updateVendorInfo(params: {
  vendorData: UpdateVendorInfoData
  files?: File[]
  creditRatingFiles?: File[]
  cashFlowRatingFiles?: File[]
  contacts: ContactInfo[]
  filesToDelete?: number[] // 삭제할 파일 ID 목록
}) {
  try {
    const {
      vendorData,
      files = [],
      creditRatingFiles = [],
      cashFlowRatingFiles = [],
      contacts,
      filesToDelete = []
    } = params

    // 세션 및 권한 확인
    const session = await getServerSession(authOptions)
    if (!session?.user || !session.user.companyId) {
      return { data: null, error: "권한이 없습니다. 로그인이 필요합니다." };
    }

    const companyId = Number(session.user.companyId);

    // 자신의 회사 정보만 수정 가능 (관리자는 모든 회사 정보 수정 가능)
    if (
      // !session.user.isAdmin && 
      vendorData.id !== companyId) {
      return { data: null, error: "자신의 회사 정보만 수정할 수 있습니다." };
    }

    // 트랜잭션으로 업데이트 수행
    await db.transaction(async (tx) => {
      // 1. 협력업체 정보 업데이트
      await tx.update(vendors).set({
        vendorName: vendorData.vendorName,
        address: vendorData.address || null,
        email: vendorData.email,
        phone: vendorData.phone || null,
        website: vendorData.website || null,
        country: vendorData.country || null,
        representativeName: vendorData.representativeName || null,
        representativeBirth: vendorData.representativeBirth || null,
        representativeEmail: vendorData.representativeEmail || null,
        representativePhone: vendorData.representativePhone || null,
        corporateRegistrationNumber: vendorData.corporateRegistrationNumber || null,
        creditAgency: vendorData.creditAgency || null,
        creditRating: vendorData.creditRating || null,
        cashFlowRating: vendorData.cashFlowRating || null,
        updatedAt: new Date(),
      }).where(eq(vendors.id, vendorData.id))

      // 2. 연락처 정보 관리
      // 2-1. 기존 연락처 가져오기
      const existingContacts = await tx
        .select()
        .from(vendorContacts)
        .where(eq(vendorContacts.vendorId, vendorData.id))

      // 2-2. 기존 연락처 ID 목록
      const existingContactIds = existingContacts.map(c => c.id)

      // 2-3. 업데이트할 연락처와 새로 추가할 연락처 분류
      const contactsToUpdate = contacts.filter(c => c.id && existingContactIds.includes(c.id))
      const contactsToAdd = contacts.filter(c => !c.id)

      // 2-4. 삭제할 연락처 (기존에 있지만 새 목록에 없는 것)
      const contactIdsToKeep = contactsToUpdate.map(c => c.id)
        .filter((id): id is number => id !== undefined)
      const contactIdsToDelete = existingContactIds.filter(id => !contactIdsToKeep.includes(id))

      // 2-5. 연락처 삭제
      if (contactIdsToDelete.length > 0) {
        await tx
          .delete(vendorContacts)
          .where(and(
            eq(vendorContacts.vendorId, vendorData.id),
            inArray(vendorContacts.id, contactIdsToDelete)
          ))
      }

      // 2-6. 연락처 업데이트
      for (const contact of contactsToUpdate) {
        if (contact.id !== undefined) {
          await tx
            .update(vendorContacts)
            .set({
              contactName: contact.contactName,
              contactPosition: contact.contactPosition || null,
              contactEmail: contact.contactEmail,
              contactPhone: contact.contactPhone || null,
              isPrimary: contact.isPrimary || false,
              updatedAt: new Date(),
            })
            .where(and(
              eq(vendorContacts.id, contact.id),
              eq(vendorContacts.vendorId, vendorData.id)
            ))
        }
      }

      // 2-7. 연락처 추가
      for (const contact of contactsToAdd) {
        await tx
          .insert(vendorContacts)
          .values({
            vendorId: vendorData.id,
            contactName: contact.contactName,
            contactPosition: contact.contactPosition || null,
            contactEmail: contact.contactEmail,
            contactPhone: contact.contactPhone || null,
            isPrimary: contact.isPrimary || false,
          })
      }

      // 3. 파일 삭제 처리
      if (filesToDelete.length > 0) {
        // 3-1. 삭제할 파일 정보 가져오기
        const attachmentsToDelete = await tx
          .select()
          .from(vendorAttachments)
          .where(and(
            eq(vendorAttachments.vendorId, vendorData.id),
            inArray(vendorAttachments.id, filesToDelete)
          ))

        // 3-2. 파일 시스템에서 파일 삭제
        for (const attachment of attachmentsToDelete) {
          try {
           
            await deleteFile(attachment.filePath)

          } catch (error) {
            console.warn(`Failed to delete file for attachment ${attachment.id}:`, error)
            // 파일 삭제 실패해도 DB에서는 삭제 진행
          }
        }

        // 3-3. DB에서 파일 기록 삭제
        await tx
          .delete(vendorAttachments)
          .where(and(
            eq(vendorAttachments.vendorId, vendorData.id),
            inArray(vendorAttachments.id, filesToDelete)
          ))
      }

      // 4. 새 파일 저장 (제공된 storeVendorFiles 함수 활용)
      // 4-1. 일반 파일 저장
      if (files.length > 0) {
        await storeVendorFiles(tx, vendorData.id, files, "GENERAL");
      }

      // 4-2. 신용평가 파일 저장
      if (creditRatingFiles.length > 0) {
        await storeVendorFiles(tx, vendorData.id, creditRatingFiles, "CREDIT_RATING");
      }

      // 4-3. 현금흐름 파일 저장
      if (cashFlowRatingFiles.length > 0) {
        await storeVendorFiles(tx, vendorData.id, cashFlowRatingFiles, "CASH_FLOW_RATING");
      }
    })

    // 캐시 무효화
    revalidateTag("vendors")
    revalidateTag(`vendor-${vendorData.id}`)

    return {
      data: {
        success: true,
        message: '협력업체 정보가 성공적으로 업데이트되었습니다.',
        vendorId: vendorData.id
      },
      error: null
    }
  } catch (error) {
    console.error("Vendor info update error:", error);
    return { data: null, error: getErrorMessage(error) }
  }
}



export interface VendorsLogWithUser {
  id: number
  vendorCandidateId: number
  userId: number
  userName: string | null
  userEmail: string | null
  action: string
  oldStatus: string | null
  newStatus: string | null
  comment: string | null
  createdAt: Date
}

export async function getVendorLogs(vendorId: number): Promise<VendorsLogWithUser[]> {
  try {
    const logs = await db
      .select({
        id: vendorsLogs.id,
        vendorCandidateId: vendorsLogs.vendorId,
        userId: vendorsLogs.userId,
        action: vendorsLogs.action,
        oldStatus: vendorsLogs.oldStatus,
        newStatus: vendorsLogs.newStatus,
        comment: vendorsLogs.comment,
        createdAt: vendorsLogs.createdAt,

        // 조인한 users 테이블 필드
        userName: users.name,
        userEmail: users.email,
      })
      .from(vendorsLogs)
      .leftJoin(users, eq(vendorsLogs.userId, users.id))
      .where(eq(vendorsLogs.vendorId, vendorId))
      .orderBy(desc(vendorsLogs.createdAt))

    return logs
  } catch (error) {
    console.error("Failed to fetch candidate logs with user info:", error)
    throw error
  }
}



/**
 * 엑셀 내보내기용 벤더 연락처 목록 조회
 * - 페이지네이션 없이 모든 연락처 반환
 */
export async function exportVendorContacts(vendorId: number) {
  try {
    const contacts = await db
      .select()
      .from(vendorContacts)
      .where(eq(vendorContacts.vendorId, vendorId))
      .orderBy(vendorContacts.isPrimary, vendorContacts.contactName);
    
    return contacts;
  } catch (error) {
    console.error("Failed to export vendor contacts:", error);
    return [];
  }
}

/**
 * 엑셀 내보내기용 벤더 아이템 목록 조회
 * - 페이지네이션 없이 모든 아이템 정보 반환
 */
export async function exportVendorItems(vendorId: number) {
  try {
    const vendorItems = await db
      .select({
        id: vendorItemsView.vendorItemId,
        vendorId: vendorItemsView.vendorId,
        itemName: vendorItemsView.itemName,
        itemCode: vendorItemsView.itemCode,
        description: vendorItemsView.description,
        createdAt: vendorItemsView.createdAt,
        updatedAt: vendorItemsView.updatedAt,
      })
      .from(vendorItemsView)
      .where(eq(vendorItemsView.vendorId, vendorId))
      .orderBy(vendorItemsView.itemName);
    
    return vendorItems;
  } catch (error) {
    console.error("Failed to export vendor items:", error);
    return [];
  }
}

/**
 * 엑셀 내보내기용 벤더 RFQ 목록 조회
 * - 페이지네이션 없이 모든 RFQ 정보 반환
 */
export async function exportVendorRFQs(vendorId: number) {
  try {
    const rfqs = await db
      .select()
      .from(vendorRfqView)
      .where(eq(vendorRfqView.vendorId, vendorId))
      .orderBy(vendorRfqView.rfqVendorUpdated);
    
    return rfqs;
  } catch (error) {
    console.error("Failed to export vendor RFQs:", error);
    return [];
  }
}

/**
 * 엑셀 내보내기용 벤더 계약 목록 조회
 * - 페이지네이션 없이 모든 계약 정보 반환
 */
export async function exportVendorContracts(vendorId: number) {
  try {
    const contracts = await db
      .select()
      .from(contractsDetailView)
      .where(eq(contractsDetailView.vendorId, vendorId))
      .orderBy(contractsDetailView.createdAt);
    
    return contracts;
  } catch (error) {
    console.error("Failed to export vendor contracts:", error);
    return [];
  }
}

/**
 * 엑셀 내보내기용 벤더 정보 조회
 * - 페이지네이션 없이 모든 벤더 정보 반환
 */
export async function exportVendorDetails(vendorIds: number[]) {
  try {
    if (!vendorIds.length) return [];
    
    // 벤더 기본 정보 조회
    const vendorsData = await db
      .select({
        id: vendors.id,
        vendorName: vendors.vendorName,
        vendorCode: vendors.vendorCode,
        taxId: vendors.taxId,
        address: vendors.address,
        country: vendors.country,
        phone: vendors.phone,
        email: vendors.email,
        website: vendors.website,
        status: vendors.status,
        representativeName: vendors.representativeName,
        representativeBirth: vendors.representativeBirth,
        representativeEmail: vendors.representativeEmail,
        representativePhone: vendors.representativePhone,
        corporateRegistrationNumber: vendors.corporateRegistrationNumber,
        creditAgency: vendors.creditAgency,
        creditRating: vendors.creditRating,
        cashFlowRating: vendors.cashFlowRating,
        createdAt: vendors.createdAt,
        updatedAt: vendors.updatedAt,
      })
      .from(vendors)
      .where(
        vendorIds.length === 1 
          ? eq(vendors.id, vendorIds[0]) 
          : inArray(vendors.id, vendorIds)
      );

    // 벤더별 상세 정보를 포함하여 반환
    const vendorsWithDetails = await Promise.all(
      vendorsData.map(async (vendor) => {
        // 연락처 조회
        const contacts = await exportVendorContacts(vendor.id);
        
        // 아이템 조회
        const items = await exportVendorItems(vendor.id);
        
        // RFQ 조회
        const rfqs = await exportVendorRFQs(vendor.id);
        
        // 계약 조회
        const contracts = await exportVendorContracts(vendor.id);
        
        return {
          ...vendor,
          vendorContacts: contacts,
          vendorItems: items,
          vendorRfqs: rfqs,
          vendorContracts: contracts,
        };
      })
    );
    
    return vendorsWithDetails;
  } catch (error) {
    console.error("Failed to export vendor details:", error);
    return [];
  }
}

/**
 * 벤더 검색 (검색어 기반, 최대 100개)
 * RFQ 벤더 추가 시 사용
 */
export async function searchVendors(searchTerm: string = "", limit: number = 100) {
  try {
    let whereCondition;
    
    if (searchTerm.trim()) {
      const s = `%${searchTerm.trim()}%`;
      whereCondition = or(
        ilike(vendorsWithTypesView.vendorName, s),
        ilike(vendorsWithTypesView.vendorCode, s)
      );
    }
    
    const vendors = await db
      .select({
        id: vendorsWithTypesView.id,
        vendorName: vendorsWithTypesView.vendorName,
        vendorCode: vendorsWithTypesView.vendorCode,
        status: vendorsWithTypesView.status,
        country: vendorsWithTypesView.country,
      })
      .from(vendorsWithTypesView)
      .where(
        and(
          whereCondition,
          // ACTIVE 상태인 벤더만 검색
          // eq(vendorsWithTypesView.status, "ACTIVE"),
        )
      )
      .orderBy(asc(vendorsWithTypesView.vendorName))
      .limit(limit);
    
    return vendors;
  } catch (error) {
    console.error("벤더 검색 오류:", error);
    return [];
  }
}

/**
 * 벤더 기본정보 조회 (Basic Info 페이지용)
 * vendorsWithTypesView를 사용하여 기본 정보 + contacts + attachments 조회
 */
export async function getVendorBasicInfo(vendorId: number) {
  unstable_noStore();
  
  try {
    return await db.transaction(async (tx) => {
      // 1. 기본 벤더 정보 조회 (vendorsWithTypesView 사용)
      const vendor = await tx
        .select()
        .from(vendorsWithTypesView)
        .where(eq(vendorsWithTypesView.id, vendorId))
        .limit(1)
        .then(rows => rows[0] || null);

      if (!vendor) {
        return null;
      }

      // 2. 연락처 정보 조회
      const contacts = await tx
        .select()
        .from(vendorContacts)
        .where(eq(vendorContacts.vendorId, vendorId))
        .orderBy(desc(vendorContacts.isPrimary), asc(vendorContacts.contactName));

      // 3. 첨부파일 정보 조회
      const attachments = await tx
        .select()
        .from(vendorAttachments)
        .where(eq(vendorAttachments.vendorId, vendorId))
        .orderBy(asc(vendorAttachments.createdAt));

      // 4. 타입 변환하여 반환 (추후 확장 가능하도록 구조화)
      return {
        // 기본 벤더 정보
        id: vendor.id,
        vendorName: vendor.vendorName,
        vendorCode: vendor.vendorCode,
        taxId: vendor.taxId,
        address: vendor.address,
        businessSize: vendor.businessSize || "", // vendorsWithTypesView에 businessSize 필드가 없을 경우 대비
        country: vendor.country,
        phone: vendor.phone,
        fax: vendor.fax || null, // vendorsWithTypesView에 fax 필드가 없을 경우 대비
        email: vendor.email,
        website: vendor.website,
        status: vendor.status,
        representativeName: vendor.representativeName,
        representativeBirth: vendor.representativeBirth,
        representativeEmail: vendor.representativeEmail,
        representativePhone: vendor.representativePhone,
        representativeWorkExperience: vendor.representativeWorkExperience ?? false, // vendorsWithTypesView에 해당 필드가 없을 경우 false로 기본값
        corporateRegistrationNumber: vendor.corporateRegistrationNumber,
        creditAgency: vendor.creditAgency,
        creditRating: vendor.creditRating,
        cashFlowRating: vendor.cashFlowRating,
        createdAt: vendor.createdAt,
        updatedAt: vendor.updatedAt,
        
        // 연락처 정보
        contacts: contacts.map(contact => ({
          id: contact.id,
          contactName: contact.contactName,
          contactPosition: contact.contactPosition,
          contactEmail: contact.contactEmail,
          contactPhone: contact.contactPhone,
          isPrimary: contact.isPrimary,
        })),
        
        // 첨부파일 정보
        attachments: attachments.map(attachment => ({
          id: attachment.id,
          fileName: attachment.fileName,
          filePath: attachment.filePath,
          attachmentType: attachment.attachmentType,
          createdAt: attachment.createdAt,
        })),
        
        // 추가 정보는 임시로 null (나중에 실제 데이터로 교체)
        additionalInfo: {
          businessType: vendor.vendorTypeId ? `Type ${vendor.vendorTypeId}` : null,
          employeeCount: 0, // 실제 데이터가 있을 수 있으므로 유지
          mainBusiness: null,
        },
        
        // 매출 정보 (구현 예정 - 나중에 실제 테이블 연결)
        salesInfo: null, // 구현 시 { "2023": { totalSales: "1000", totalDebt: "500", ... }, "2022": { ... } } 형태로 연도별 키 사용
        
        // 추가 정보들 (구현 예정 - 나중에 실제 테이블 연결)
        organization: null,
        
        factoryInfo: null,
        
        inspectionInfo: null,
        
        evaluationInfo: null,
        
        classificationInfo: {
          vendorClassification: null,
          groupCompany: null,
          preferredLanguage: "한국어", // 기본값으로 유지
          industryType: "제조업", // 기본값으로 유지
          isoCertification: null,
        },
        
        contractDetails: null,
        
        capacityInfo: null,
        
        calculatedMetrics: null, // 구현 시 { "20231231": { debtRatio: 0, ... }, "20221231": { ... } } 형태로 YYYYMMDD 키 사용
      };
    });
  } catch (error) {
    console.error("Error fetching vendor basic info:", error);
    return null;
  }
}