summaryrefslogtreecommitdiff
path: root/lib/tech-vendors/service.ts
blob: 72f8632d20f3c9945c5f2662584c179c3ca01bb9 (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
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택)

import { revalidateTag, unstable_noStore } from "next/cache";
import db from "@/db/db";
import { techVendorAttachments, techVendorContacts, techVendorPossibleItems, techVendors, type TechVendor } from "@/db/schema/techVendors";
import { itemShipbuilding, itemOffshoreTop, itemOffshoreHull } from "@/db/schema/items";
import { users } from "@/db/schema/users";
import ExcelJS from "exceljs";
import { filterColumns } from "@/lib/filter-columns";
import { unstable_cache } from "@/lib/unstable-cache";
import { getErrorMessage } from "@/lib/handle-error";

import {
  insertTechVendor,
  updateTechVendor,
  groupByTechVendorStatus,
  selectTechVendorContacts,
  countTechVendorContacts,
  insertTechVendorContact,
  selectTechVendorsWithAttachments,
  countTechVendorsWithAttachments,
} from "./repository";

import type {
  CreateTechVendorSchema,
  UpdateTechVendorSchema,
  GetTechVendorsSchema,
  GetTechVendorContactsSchema,
  CreateTechVendorContactSchema,
  GetTechVendorItemsSchema,
  GetTechVendorRfqHistorySchema,
  GetTechVendorPossibleItemsSchema,
  CreateTechVendorPossibleItemSchema,
  UpdateTechVendorContactSchema,
} from "./validations";

import { asc, desc, ilike, inArray, and, or, eq, isNull, not } from "drizzle-orm";
import path from "path";
import { sql } from "drizzle-orm";
import { decryptWithServerAction } from "@/components/drm/drmUtils";
import { deleteFile, saveDRMFile } from "../file-stroage";
import { techSalesContactPossibleItems } from "@/db/schema";

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

/**
 * 복잡한 조건으로 기술영업 Vendor 목록을 조회 (+ pagination) 하고,
 * 총 개수에 따라 pageCount를 계산해서 리턴.
 * Next.js의 unstable_cache를 사용해 일정 시간 캐시.
 */
export async function getTechVendors(input: GetTechVendorsSchema) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;
        
        // 1) 고급 필터 (workTypes와 techVendorType 제외 - 별도 처리)
        const filteredFilters = input.filters.filter(
          filter => filter.id !== "workTypes" && filter.id !== "techVendorType"
        );
        
        const advancedWhere = filterColumns({
          table: techVendors,
          filters: filteredFilters,
          joinOperator: input.joinOperator,
        });
        
        // 2) 글로벌 검색
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(techVendors.vendorName, s),
            ilike(techVendors.vendorCode, s),
            ilike(techVendors.email, s),
            ilike(techVendors.status, s)
          );
        }
        
        // 최종 where 결합
        const finalWhere = and(advancedWhere, globalWhere);
        
        // 벤더 타입 필터링 로직 추가
        let vendorTypeWhere;
        if (input.vendorType) {
          // URL의 vendorType 파라미터를 실제 벤더 타입으로 매핑
          const vendorTypeMap = {
            "ship": "조선",
            "top": "해양TOP", 
            "hull": "해양HULL"
          };
          
          const actualVendorType = input.vendorType in vendorTypeMap 
            ? vendorTypeMap[input.vendorType as keyof typeof vendorTypeMap]
            : undefined;
          if (actualVendorType) {
            // techVendorType 필드는 콤마로 구분된 문자열이므로 LIKE 사용
            vendorTypeWhere = ilike(techVendors.techVendorType, `%${actualVendorType}%`);
          }
        }

        // 간단 검색 (advancedTable=false) 시 예시
        const simpleWhere = and(
          input.vendorName
            ? ilike(techVendors.vendorName, `%${input.vendorName}%`)
            : undefined,
          input.status ? ilike(techVendors.status, input.status) : undefined,
          input.country
            ? ilike(techVendors.country, `%${input.country}%`)
            : undefined
        );
        
        // TechVendorType 필터링 로직 추가 (고급 필터에서)
        let techVendorTypeWhere;
        const techVendorTypeFilters = input.filters.filter(filter => filter.id === "techVendorType");
        if (techVendorTypeFilters.length > 0) {
          const typeFilter = techVendorTypeFilters[0];
          if (Array.isArray(typeFilter.value) && typeFilter.value.length > 0) {
            // 각 타입에 대해 LIKE 조건으로 OR 연결
            const typeConditions = typeFilter.value.map(type =>
              ilike(techVendors.techVendorType, `%${type}%`)
            );
            techVendorTypeWhere = or(...typeConditions);
          }
        }

        // WorkTypes 필터링 로직 추가
        let workTypesWhere;
        const workTypesFilters = input.filters.filter(filter => filter.id === "workTypes");
        if (workTypesFilters.length > 0) {
          const workTypeFilter = workTypesFilters[0];
          if (Array.isArray(workTypeFilter.value) && workTypeFilter.value.length > 0) {
            // workTypes에 해당하는 벤더 ID들을 서브쿼리로 찾음
            const vendorIdsWithWorkTypes = db
              .selectDistinct({ vendorId: techVendorPossibleItems.vendorId })
              .from(techVendorPossibleItems)
              .leftJoin(itemShipbuilding, eq(techVendorPossibleItems.shipbuildingItemId, itemShipbuilding.id))
              .leftJoin(itemOffshoreTop, eq(techVendorPossibleItems.offshoreTopItemId, itemOffshoreTop.id))
              .leftJoin(itemOffshoreHull, eq(techVendorPossibleItems.offshoreHullItemId, itemOffshoreHull.id))
              .where(
                or(
                  inArray(itemShipbuilding.workType, workTypeFilter.value),
                  inArray(itemOffshoreTop.workType, workTypeFilter.value),
                  inArray(itemOffshoreHull.workType, workTypeFilter.value)
                )
              );

            workTypesWhere = inArray(techVendors.id, vendorIdsWithWorkTypes);
          }
        }

        // 실제 사용될 where (vendorType, techVendorType, workTypes 필터링 추가)
        const where = and(finalWhere, vendorTypeWhere, techVendorTypeWhere, workTypesWhere);
        
        // 정렬
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(techVendors[item.id]) : asc(techVendors[item.id])
            )
            : [asc(techVendors.createdAt)];
        
        // 트랜잭션 내에서 데이터 조회
        const { data, total } = await db.transaction(async (tx) => {
          // 1) vendor 목록 조회 (with attachments)
          const vendorsData = await selectTechVendorsWithAttachments(tx, {
            where,
            orderBy,
            offset,
            limit: input.perPage,
          });
          
          // 2) 전체 개수
          const total = await countTechVendorsWithAttachments(tx, where);
          return { data: vendorsData, total };
        });
        
        // 페이지 수
        const pageCount = Math.ceil(total / input.perPage);
        
        return { data, pageCount };
      } catch (err) {
        console.error("Error fetching tech vendors:", err);
        // 에러 발생 시
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input)], // 캐싱 키
    {
      revalidate: 3600,
      tags: ["tech-vendors"], // revalidateTag("tech-vendors") 호출 시 무효화
    }
  )();
}

/**
 * 기술영업 벤더 상태별 카운트 조회
 */
export async function getTechVendorStatusCounts() {
  return unstable_cache(
    async () => {
      try {
        const initial: Record<TechVendor["status"], number> = {
          "PENDING_INVITE": 0,
          "INVITED": 0,
          "QUOTE_COMPARISON": 0,
          "ACTIVE": 0,
          "INACTIVE": 0,
          "BLACKLISTED": 0,
        };

        const result = await db.transaction(async (tx) => {
          const rows = await groupByTechVendorStatus(tx);
          type StatusCountRow = { status: TechVendor["status"]; count: number };
          return (rows as StatusCountRow[]).reduce<Record<TechVendor["status"], number>>((acc, { status, count }) => {
            acc[status] = count;
            return acc;
          }, initial);
        });

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

/**
 * 벤더 상세 정보 조회
 */
export async function getTechVendorById(id: number) {
  return unstable_cache(
    async () => {
      try {
        const result = await getTechVendorDetailById(id);
        return { data: result };
      } catch (err) {
        console.error("기술영업 벤더 상세 조회 오류:", err);
        return { data: null };
      }
    },
    [`tech-vendor-${id}`],
    {
      revalidate: 3600,
      tags: ["tech-vendors", `tech-vendor-${id}`],
    }
  )();
}

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

/**
 * 첨부파일 저장 헬퍼 함수
 */
async function storeTechVendorFiles(
  tx: any,
  vendorId: number,
  files: File[],
  attachmentType: string
) {

  for (const file of files) {

    const saveResult = await saveDRMFile(file, decryptWithServerAction, `tech-vendors/${vendorId}`)

    // Insert attachment record
    await tx.insert(techVendorAttachments).values({
      vendorId,
      fileName: file.name,
      filePath: saveResult.publicPath,
      attachmentType,
    });
  }
}

/**
 * 신규 기술영업 벤더 생성
 */
export async function createTechVendor(input: CreateTechVendorSchema) {
  unstable_noStore();
  
  try {
    // 이메일 중복 검사
    const existingVendorByEmail = await db
      .select({ id: techVendors.id, vendorName: techVendors.vendorName })
      .from(techVendors)
      .where(eq(techVendors.email, input.email))
      .limit(1);
    
    // 이미 동일한 이메일을 가진 업체가 존재하면 에러 반환
    if (existingVendorByEmail.length > 0) {
      return {
        success: false,
        data: null,
        error: `이미 등록된 이메일입니다. (업체명: ${existingVendorByEmail[0].vendorName})`
      };
    }

    // taxId 중복 검사
    const existingVendorByTaxId = await db
      .select({ id: techVendors.id })
      .from(techVendors)
      .where(eq(techVendors.taxId, input.taxId))
      .limit(1);
    
    // 이미 동일한 taxId를 가진 업체가 존재하면 에러 반환
    if (existingVendorByTaxId.length > 0) {
      return {
        success: false,
        data: null,
        error: `이미 등록된 사업자등록번호입니다. (Tax ID ${input.taxId} already exists in the system)`
      };
    }
    
    const result = await db.transaction(async (tx) => {
      // 1. 벤더 생성
      const [newVendor] = await insertTechVendor(tx, {
        vendorName: input.vendorName,
        vendorCode: input.vendorCode || null,
        taxId: input.taxId,
        address: input.address || null,
        country: input.country,
        countryEng: null,
        countryFab: null,
        agentName: null,
        agentPhone: null,
        agentEmail: null,
        phone: input.phone || null,
        email: input.email,
        website: input.website || null,
        techVendorType: Array.isArray(input.techVendorType) ? input.techVendorType.join(',') : input.techVendorType,
        representativeName: input.representativeName || null,
        representativeBirth: input.representativeBirth || null,
        representativeEmail: input.representativeEmail || null,
        representativePhone: input.representativePhone || null,
        items: input.items || null,
        status: "ACTIVE",
        isQuoteComparison: false,
      });
      
      // 2. 연락처 정보 등록
      for (const contact of input.contacts) {
        await insertTechVendorContact(tx, {
          vendorId: newVendor.id,
          contactName: contact.contactName,
          contactPosition: contact.contactPosition || null,
          contactEmail: contact.contactEmail,
          contactPhone: contact.contactPhone || null,
          isPrimary: contact.isPrimary ?? false,
          contactCountry: contact.contactCountry || null,
          contactTitle: contact.contactTitle || null,
        });
      }
      
      // 3. 첨부파일 저장
      if (input.files && input.files.length > 0) {
        await storeTechVendorFiles(tx, newVendor.id, input.files, "GENERAL");
      }
      
      return newVendor;
    });
    
    revalidateTag("tech-vendors");
    
    return {
      success: true,
      data: result,
      error: null
    };
  } catch (err) {
    console.error("기술영업 벤더 생성 오류:", err);
    
    return {
      success: false,
      data: null,
      error: getErrorMessage(err)
    };
  }
}

/* -----------------------------------------------------
   3) 업데이트 (단건/복수)
----------------------------------------------------- */

/** 단건 업데이트 */
export async function modifyTechVendor(
  input: UpdateTechVendorSchema & { id: string; }
) {
  unstable_noStore();
  try {
    const updated = await db.transaction(async (tx) => {
      // 벤더 정보 업데이트
      const [res] = await updateTechVendor(tx, input.id, {
        vendorName: input.vendorName,
        vendorCode: input.vendorCode,
        address: input.address,
        country: input.country,
        countryEng: input.countryEng,
        countryFab: input.countryFab,
        phone: input.phone,
        email: input.email,
        website: input.website,
        status: input.status,
        // 에이전트 정보 추가
        agentName: input.agentName,
        agentEmail: input.agentEmail,
        agentPhone: input.agentPhone,
        // 대표자 정보 추가
        representativeName: input.representativeName,
        representativeEmail: input.representativeEmail,
        representativePhone: input.representativePhone,
        representativeBirth: input.representativeBirth,
        // techVendorType 처리
        techVendorType: Array.isArray(input.techVendorType) ? input.techVendorType.join(',') : input.techVendorType,
      });

      return res;
    });

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

    return { data: updated, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}
/* -----------------------------------------------------
   4) 연락처 관리
----------------------------------------------------- */

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

        // 필터링 설정
        const advancedWhere = filterColumns({
          table: techVendorContacts,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });

        // 검색 조건
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(techVendorContacts.contactName, s), 
            ilike(techVendorContacts.contactPosition, s),
            ilike(techVendorContacts.contactEmail, s), 
            ilike(techVendorContacts.contactPhone, s)
          );
        }

        // 해당 벤더 조건
        const vendorWhere = eq(techVendorContacts.vendorId, id);

        // 최종 조건 결합
        const finalWhere = and(advancedWhere, globalWhere, vendorWhere);

        // 정렬 조건
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(techVendorContacts[item.id]) : asc(techVendorContacts[item.id])
            )
            : [asc(techVendorContacts.createdAt)];

        // 트랜잭션 내부에서 Repository 호출
        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectTechVendorContacts(tx, {
            where: finalWhere,
            orderBy,
            offset,
            limit: input.perPage,
          });
          const total = await countTechVendorContacts(tx, finalWhere);
          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: [`tech-vendor-contacts-${id}`],
    }
  )();
}

export async function createTechVendorContact(input: CreateTechVendorContactSchema) {
  unstable_noStore();
  try {
    await db.transaction(async (tx) => {
      // DB Insert
      const [newContact] = await insertTechVendorContact(tx, {
        vendorId: input.vendorId,
        contactName: input.contactName,
        contactPosition: input.contactPosition || "",
        contactEmail: input.contactEmail,
        contactPhone: input.contactPhone || "",
        contactCountry: input.contactCountry || "",
        isPrimary: input.isPrimary || false,
        contactTitle: input.contactTitle || "",
      });
      
      return newContact;
    });

    // 캐시 무효화
    revalidateTag(`tech-vendor-contacts-${input.vendorId}`);
    revalidateTag("users");

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

export async function updateTechVendorContact(input: UpdateTechVendorContactSchema & { id: number; vendorId: number }) {
  unstable_noStore();
  try {
    const [updatedContact] = await db
      .update(techVendorContacts)
      .set({
        contactName: input.contactName,
        contactPosition: input.contactPosition || null,
        contactEmail: input.contactEmail,
        contactPhone: input.contactPhone || null,
        contactCountry: input.contactCountry || null,
        isPrimary: input.isPrimary || false,
        contactTitle: input.contactTitle || null,
        updatedAt: new Date(),
      })
      .where(eq(techVendorContacts.id, input.id))
      .returning();

    // 캐시 무효화
    revalidateTag(`tech-vendor-contacts-${input.vendorId}`);
    revalidateTag("users");

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

export async function deleteTechVendorContact(contactId: number, vendorId: number) {
  unstable_noStore();
  try {
    const [deletedContact] = await db
      .delete(techVendorContacts)
      .where(eq(techVendorContacts.id, contactId))
      .returning();

    // 캐시 무효화
    revalidateTag(`tech-vendor-contacts-${contactId}`);
    revalidateTag(`tech-vendor-contacts-${vendorId}`);

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

/* -----------------------------------------------------
   5) 아이템 관리
----------------------------------------------------- */

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

        // 벤더 ID 조건
        const vendorWhere = eq(techVendorPossibleItems.vendorId, id);

        // 조선 아이템들 조회
        const shipItems = await db
          .select({
            id: techVendorPossibleItems.id,
            vendorId: techVendorPossibleItems.vendorId,
            shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
            offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
            offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
            createdAt: techVendorPossibleItems.createdAt,
            updatedAt: techVendorPossibleItems.updatedAt,
            itemCode: itemShipbuilding.itemCode,
            workType: itemShipbuilding.workType,
            itemList: itemShipbuilding.itemList,
            shipTypes: itemShipbuilding.shipTypes,
            subItemList: sql<string>`null`.as("subItemList"),
            techVendorType: techVendors.techVendorType,
          })
          .from(techVendorPossibleItems)
          .leftJoin(itemShipbuilding, eq(techVendorPossibleItems.shipbuildingItemId, itemShipbuilding.id))
          .leftJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .where(and(vendorWhere, not(isNull(techVendorPossibleItems.shipbuildingItemId))));

        // 해양 TOP 아이템들 조회
        const topItems = await db
          .select({
            id: techVendorPossibleItems.id,
            vendorId: techVendorPossibleItems.vendorId,
            shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
            offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
            offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
            createdAt: techVendorPossibleItems.createdAt,
            updatedAt: techVendorPossibleItems.updatedAt,
            itemCode: itemOffshoreTop.itemCode,
            workType: itemOffshoreTop.workType,
            itemList: itemOffshoreTop.itemList,
            shipTypes: sql<string>`null`.as("shipTypes"),
            subItemList: itemOffshoreTop.subItemList,
            techVendorType: techVendors.techVendorType,
          })
          .from(techVendorPossibleItems)
          .leftJoin(itemOffshoreTop, eq(techVendorPossibleItems.offshoreTopItemId, itemOffshoreTop.id))
          .leftJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .where(and(vendorWhere, not(isNull(techVendorPossibleItems.offshoreTopItemId))));

        // 해양 HULL 아이템들 조회
        const hullItems = await db
          .select({
            id: techVendorPossibleItems.id,
            vendorId: techVendorPossibleItems.vendorId,
            shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
            offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
            offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
            createdAt: techVendorPossibleItems.createdAt,
            updatedAt: techVendorPossibleItems.updatedAt,
            itemCode: itemOffshoreHull.itemCode,
            workType: itemOffshoreHull.workType,
            itemList: itemOffshoreHull.itemList,
            shipTypes: sql<string>`null`.as("shipTypes"),
            subItemList: itemOffshoreHull.subItemList,
            techVendorType: techVendors.techVendorType,
          })
          .from(techVendorPossibleItems)
          .leftJoin(itemOffshoreHull, eq(techVendorPossibleItems.offshoreHullItemId, itemOffshoreHull.id))
          .leftJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .where(and(vendorWhere, not(isNull(techVendorPossibleItems.offshoreHullItemId))));

        // 모든 아이템들 합치기
        const allItems = [...shipItems, ...topItems, ...hullItems];

        // 필터링 적용
        let filteredItems = allItems;

        if (input.search) {
          const s = input.search.toLowerCase();
          filteredItems = filteredItems.filter(item => 
            item.itemCode?.toLowerCase().includes(s) ||
            item.workType?.toLowerCase().includes(s) ||
            item.itemList?.toLowerCase().includes(s) ||
            item.shipTypes?.toLowerCase().includes(s) ||
            item.subItemList?.toLowerCase().includes(s)
          );
        }

        // 정렬 적용
        if (input.sort.length > 0) {
          const sortConfig = input.sort[0];
          filteredItems.sort((a, b) => {
            const aVal = a[sortConfig.id as keyof typeof a];
            const bVal = b[sortConfig.id as keyof typeof b];
            
            if (aVal == null && bVal == null) return 0;
            if (aVal == null) return sortConfig.desc ? 1 : -1;
            if (bVal == null) return sortConfig.desc ? -1 : 1;
            
            const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
            return sortConfig.desc ? -comparison : comparison;
          });
        }

        // 페이지네이션 적용
        const total = filteredItems.length;
        const paginatedItems = filteredItems.slice(offset, offset + input.perPage);
        const pageCount = Math.ceil(total / input.perPage);

        return { data: paginatedItems, pageCount };
      } catch (err) {
        console.error("기술영업 벤더 아이템 조회 오류:", err);
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input), String(id)], // 캐싱 키
    {
      revalidate: 3600,
      tags: [`tech-vendor-items-${id}`],
    }
  )();
}

export interface ItemDropdownOption {
  itemCode: string;
  itemList: string;
  workType: string | null;
  shipTypes: string | null;
  subItemList: string | null;
}

/**
 * Vendor Item 추가 시 사용할 아이템 목록 조회 (전체 목록 반환)
 * 아이템 코드, 이름, 설명만 간소화해서 반환
 */
export async function getItemsForTechVendor(vendorId: number) {
  return unstable_cache(
    async () => {
      try {
        // 1. 벤더 정보 조회로 벤더 타입 확인
        const vendor = await db.query.techVendors.findFirst({
          where: eq(techVendors.id, vendorId),
          columns: {
            techVendorType: true
          }
        });

        if (!vendor) {
          return {
            data: [],
            error: "벤더를 찾을 수 없습니다.",
          };
        }

        // 2. 해당 벤더가 이미 가지고 있는 아이템 ID 목록 조회
        const existingItems = await db
          .select({
            shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
            offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
            offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
          })
          .from(techVendorPossibleItems)
          .where(eq(techVendorPossibleItems.vendorId, vendorId));

        const existingShipItemIds = existingItems.map(item => item.shipbuildingItemId).filter(id => id !== null);
        const existingTopItemIds = existingItems.map(item => item.offshoreTopItemId).filter(id => id !== null);
        const existingHullItemIds = existingItems.map(item => item.offshoreHullItemId).filter(id => id !== null);

        // 3. 벤더 타입에 따라 해당 타입의 아이템만 조회 (기존에 없는 것만)
        const availableItems: Array<{
          id: number;
          itemCode: string | null;
          itemList: string | null;
          workType: string | null;
          shipTypes?: string | null;
          subItemList?: string | null;
          itemType: "SHIP" | "TOP" | "HULL";
          createdAt: Date;
          updatedAt: Date;
        }> = [];

        // 벤더 타입 파싱 - 콤마로 구분된 문자열을 배열로 변환
        let vendorTypes: string[] = [];
        if (typeof vendor.techVendorType === 'string') {
          // 콤마로 구분된 문자열을 split하여 배열로 변환하고 공백 제거
          vendorTypes = vendor.techVendorType.split(',').map(type => type.trim()).filter(type => type.length > 0);
        } else {
          vendorTypes = [vendor.techVendorType];
        }

        // 각 벤더 타입별로 아이템 조회
        for (const vendorType of vendorTypes) {
          if (vendorType === "조선") {
            const shipbuildingItems = await db
              .select({
                id: itemShipbuilding.id,
                createdAt: itemShipbuilding.createdAt,
                updatedAt: itemShipbuilding.updatedAt,
                itemCode: itemShipbuilding.itemCode,
                itemList: itemShipbuilding.itemList,
                workType: itemShipbuilding.workType,
                shipTypes: itemShipbuilding.shipTypes,
              })
              .from(itemShipbuilding)
              .where(
                existingShipItemIds.length > 0 
                  ? not(inArray(itemShipbuilding.id, existingShipItemIds))
                  : undefined
              )
              .orderBy(asc(itemShipbuilding.itemCode));

            availableItems.push(...shipbuildingItems
              .filter(item => item.itemCode != null)
              .map(item => ({
                id: item.id,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
                itemCode: item.itemCode,
                itemList: item.itemList,
                workType: item.workType,
                shipTypes: item.shipTypes,
                itemType: "SHIP" as const
              })));
          }

          if (vendorType === "해양TOP") {
            const offshoreTopItems = await db
              .select({
                id: itemOffshoreTop.id,
                createdAt: itemOffshoreTop.createdAt,
                updatedAt: itemOffshoreTop.updatedAt,
                itemCode: itemOffshoreTop.itemCode,
                itemList: itemOffshoreTop.itemList,
                workType: itemOffshoreTop.workType,
                subItemList: itemOffshoreTop.subItemList,
              })
              .from(itemOffshoreTop)
              .where(
                existingTopItemIds.length > 0 
                  ? not(inArray(itemOffshoreTop.id, existingTopItemIds))
                  : undefined
              )
              .orderBy(asc(itemOffshoreTop.itemCode));

            availableItems.push(...offshoreTopItems
              .filter(item => item.itemCode != null)
              .map(item => ({
                id: item.id,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
                itemCode: item.itemCode,
                itemList: item.itemList,
                workType: item.workType,
                subItemList: item.subItemList,
                itemType: "TOP" as const
              })));
          }

          if (vendorType === "해양HULL") {
            const offshoreHullItems = await db
              .select({
                id: itemOffshoreHull.id,
                createdAt: itemOffshoreHull.createdAt,
                updatedAt: itemOffshoreHull.updatedAt,
                itemCode: itemOffshoreHull.itemCode,
                itemList: itemOffshoreHull.itemList,
                workType: itemOffshoreHull.workType,
                subItemList: itemOffshoreHull.subItemList,
              })
              .from(itemOffshoreHull)
              .where(
                existingHullItemIds.length > 0 
                  ? not(inArray(itemOffshoreHull.id, existingHullItemIds))
                  : undefined
              )
              .orderBy(asc(itemOffshoreHull.itemCode));

            availableItems.push(...offshoreHullItems
              .filter(item => item.itemCode != null)
              .map(item => ({
                id: item.id,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
                itemCode: item.itemCode,
                itemList: item.itemList,
                workType: item.workType,
                subItemList: item.subItemList,
                itemType: "HULL" as const
              })));
          }
        }

        // 중복 제거 (같은 id와 itemType을 가진 아이템)
        const uniqueItems = availableItems.filter((item, index, self) =>
          index === self.findIndex((t) => t.id === item.id && t.itemType === item.itemType)
        );

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

/**
 * 벤더 타입과 아이템 코드에 따른 아이템 조회
 */
export async function getItemsByVendorType(vendorType: string, itemCode: string) {
  try {
    let items: (typeof itemShipbuilding.$inferSelect | typeof itemOffshoreTop.$inferSelect | typeof itemOffshoreHull.$inferSelect)[] = [];
    
    switch (vendorType) {
      case "조선":
        const shipbuildingResults = await db
          .select({
            id: itemShipbuilding.id,
            itemCode: itemShipbuilding.itemCode,
            workType: itemShipbuilding.workType,
            shipTypes: itemShipbuilding.shipTypes,
            itemList: itemShipbuilding.itemList,
            createdAt: itemShipbuilding.createdAt,
            updatedAt: itemShipbuilding.updatedAt,
          })
          .from(itemShipbuilding)
          .where(itemCode ? eq(itemShipbuilding.itemCode, itemCode) : undefined);
        items = shipbuildingResults;
        break;

      case "해양TOP":
        const offshoreTopResults = await db
          .select({
            id: itemOffshoreTop.id,
            itemCode: itemOffshoreTop.itemCode,
            workType: itemOffshoreTop.workType,
            itemList: itemOffshoreTop.itemList,
            subItemList: itemOffshoreTop.subItemList,
            createdAt: itemOffshoreTop.createdAt,
            updatedAt: itemOffshoreTop.updatedAt,
          })
          .from(itemOffshoreTop)
          .where(itemCode ? eq(itemOffshoreTop.itemCode, itemCode) : undefined);
        items = offshoreTopResults;
        break;

      case "해양HULL":
        const offshoreHullResults = await db
          .select({
            id: itemOffshoreHull.id,
            itemCode: itemOffshoreHull.itemCode,
            workType: itemOffshoreHull.workType,
            itemList: itemOffshoreHull.itemList,
            subItemList: itemOffshoreHull.subItemList,
            createdAt: itemOffshoreHull.createdAt,
            updatedAt: itemOffshoreHull.updatedAt,
          })
          .from(itemOffshoreHull)
          .where(itemCode ? eq(itemOffshoreHull.itemCode, itemCode) : undefined);
        items = offshoreHullResults;
        break;

      default:
        items = [];
    }

    const result = items.map(item => ({
      ...item,
      techVendorType: vendorType
    }));

    return { data: result, error: null };
  } catch (err) {
    console.error("Error fetching items by vendor type:", err);
    return { data: [], error: "Failed to fetch items" };
  }
}

/* -----------------------------------------------------
   6) 기술영업 벤더 승인/거부
----------------------------------------------------- */

interface ApproveTechVendorsInput {
  ids: string[];
}

/**
 * 기술영업 벤더 승인 (상태를 ACTIVE로 변경)
 */
export async function approveTechVendors(input: ApproveTechVendorsInput) {
  unstable_noStore();
  
  try {
    // 트랜잭션 내에서 협력업체 상태 업데이트
    const result = await db.transaction(async (tx) => {
      // 협력업체 상태 업데이트
      const [updated] = await tx
        .update(techVendors)
        .set({
          status: "ACTIVE",
          updatedAt: new Date()
        })
        .where(inArray(techVendors.id, input.ids.map(id => parseInt(id))))
        .returning();
        
      return updated;
    });
    
    // 캐시 무효화
    revalidateTag("tech-vendors");
    revalidateTag("tech-vendor-status-counts");
    
    return { data: result, error: null };
  } catch (err) {
    console.error("Error approving tech vendors:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 벤더 거부 (상태를 REJECTED로 변경)
 */
export async function rejectTechVendors(input: ApproveTechVendorsInput) {
  unstable_noStore();
  
  try {
    // 트랜잭션 내에서 협력업체 상태 업데이트
    const result = await db.transaction(async (tx) => {
      // 협력업체 상태 업데이트
      const [updated] = await tx
        .update(techVendors)
        .set({
          status: "INACTIVE",
          updatedAt: new Date()
        })
        .where(inArray(techVendors.id, input.ids.map(id => parseInt(id))))
        .returning();
        
      return updated;
    });
    
    // 캐시 무효화
    revalidateTag("tech-vendors");
    revalidateTag("tech-vendor-status-counts");
    
    return { data: result, error: null };
  } catch (err) {
    console.error("Error rejecting tech vendors:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/* -----------------------------------------------------
   7) 엑셀 내보내기
----------------------------------------------------- */

/**
 * 벤더 연락처 목록 엑셀 내보내기
 */
export async function exportTechVendorContacts(vendorId: number) {
  try {
    const contacts = await db
      .select()
      .from(techVendorContacts)
      .where(eq(techVendorContacts.vendorId, vendorId))
      .orderBy(techVendorContacts.isPrimary, techVendorContacts.contactName);
    
    return contacts;
  } catch (err) {
    console.error("기술영업 벤더 연락처 내보내기 오류:", err);
    return [];
  }
}


/**
 * 벤더 정보 엑셀 내보내기
 */
export async function exportTechVendorDetails(vendorIds: number[]) {
  try {
    if (!vendorIds.length) return [];
    
    // 벤더 기본 정보 조회
    const vendorsData = await db
      .select({
        id: techVendors.id,
        vendorName: techVendors.vendorName,
        vendorCode: techVendors.vendorCode,
        taxId: techVendors.taxId,
        address: techVendors.address,
        country: techVendors.country,
        phone: techVendors.phone,
        email: techVendors.email,
        website: techVendors.website,
        status: techVendors.status,
        representativeName: techVendors.representativeName,
        representativeEmail: techVendors.representativeEmail,
        representativePhone: techVendors.representativePhone,
        representativeBirth: techVendors.representativeBirth,
        items: techVendors.items,
        createdAt: techVendors.createdAt,
        updatedAt: techVendors.updatedAt,
      })
      .from(techVendors)
      .where(
        vendorIds.length === 1 
          ? eq(techVendors.id, vendorIds[0]) 
          : inArray(techVendors.id, vendorIds)
      );

    // 벤더별 상세 정보를 포함하여 반환
    const vendorsWithDetails = await Promise.all(
      vendorsData.map(async (vendor) => {
        // 연락처 조회
        const contacts = await exportTechVendorContacts(vendor.id);
        
        // // 아이템 조회
        // const items = await exportTechVendorItems(vendor.id);
        
        return {
          ...vendor,
          vendorContacts: contacts,
          // vendorItems: items,
        };
      })
    );
    
    return vendorsWithDetails;
  } catch (err) {
    console.error("기술영업 벤더 상세 내보내기 오류:", err);
    return [];
  }
}

/**
 * 기술영업 벤더 상세 정보 조회 (연락처, 첨부파일 포함)
 */
export async function getTechVendorDetailById(id: number) {
  try {
    const vendor = await db.select().from(techVendors).where(eq(techVendors.id, id)).limit(1);
    
    if (!vendor || vendor.length === 0) {
      console.error(`Vendor not found with id: ${id}`);
      return null;
    }

    const contacts = await db.select().from(techVendorContacts).where(eq(techVendorContacts.vendorId, id));
    const attachments = await db.select().from(techVendorAttachments).where(eq(techVendorAttachments.vendorId, id));
    const possibleItems = await db.select().from(techVendorPossibleItems).where(eq(techVendorPossibleItems.vendorId, id));

    return {
      ...vendor[0],
      contacts,
      attachments,
      possibleItems
    };
  } catch (error) {
    console.error("Error fetching tech vendor detail:", error);
    return null;
  }
}

/**
 * 기술영업 벤더 첨부파일 다운로드를 위한 서버 액션
 * @param vendorId 기술영업 벤더 ID
 * @param fileId 특정 파일 ID (단일 파일 다운로드시)
 * @returns 다운로드할 수 있는 임시 URL
 */
export async function downloadTechVendorAttachments(vendorId:number, fileId?:number) {
  try {
    // API 경로 생성 (단일 파일 또는 모든 파일)
    const path = fileId
      ? `/api/tech-vendors/attachments/download?id=${fileId}&vendorId=${vendorId}`
      : `/api/tech-vendors/attachments/download-all?vendorId=${vendorId}`;
    
    // 서버에서는 URL만 반환하고, 클라이언트에서 실제 다운로드 처리
    // 파일명도 기본값으로 설정
    const fileName = fileId ? `file-${fileId}.zip` : `tech-vendor-${vendorId}-attachments.zip`;
    
    return { 
      url: path, // 상대 경로 반환
      fileName,
      isServerAction: true // 서버 액션임을 표시
    };
  } catch (error) {
    console.error('Download API error:', error);
    throw error;
  }
}

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

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

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

export const findVendorById = async (id: number): Promise<TechVendor | null> => {
  try {
    // 직접 DB에서 조회
    const vendor = await db
      .select()
      .from(techVendors)
      .where(eq(techVendors.id, id))
      .limit(1)
      .then(rows => rows[0] || null);

    if (!vendor) {
      console.error(`Vendor not found with id: ${id}`);
      return null;
    }

    return vendor;
  } catch (error) {
    console.error('Error fetching vendor:', error);
    return null;
  }
};

/* -----------------------------------------------------
   8) 기술영업 벤더 RFQ 히스토리 조회
----------------------------------------------------- */

/**
 * 기술영업 벤더의 RFQ 히스토리 조회 (간단한 버전)
 */
export async function getTechVendorRfqHistory(input: GetTechVendorRfqHistorySchema, id:number) {
  try {

    // 먼저 해당 벤더의 견적서가 있는지 확인
    const { techSalesVendorQuotations } = await import("@/db/schema/techSales");
    
    const quotationCheck = await db
      .select({ count: sql<number>`count(*)`.as("count") })
      .from(techSalesVendorQuotations)
      .where(eq(techSalesVendorQuotations.vendorId, id));
    
    console.log(`벤더 ${id}의 견적서 개수:`, quotationCheck[0]?.count);

    if (quotationCheck[0]?.count === 0) {
      console.log("해당 벤더의 견적서가 없습니다.");
      return { data: [], pageCount: 0 };
    }

    const offset = (input.page - 1) * input.perPage;
    const { techSalesRfqs } = await import("@/db/schema/techSales");
    const { biddingProjects } = await import("@/db/schema/projects");

    // 간단한 조회
    let whereCondition = eq(techSalesVendorQuotations.vendorId, id);
    
    // 검색이 있다면 추가
    if (input.search) {
      const s = `%${input.search}%`;
      const searchCondition = and(
        whereCondition,
        or(
          ilike(techSalesRfqs.rfqCode, s),
          ilike(techSalesRfqs.description, s),
          ilike(biddingProjects.pspid, s),
          ilike(biddingProjects.projNm, s)
        )
      );
      whereCondition = searchCondition || whereCondition;
    }

    // 데이터 조회 - 테이블에 필요한 필드들 (프로젝트 타입 추가)
    const data = await db
      .select({
        id: techSalesRfqs.id,
        rfqCode: techSalesRfqs.rfqCode,
        description: techSalesRfqs.description,
        projectCode: biddingProjects.pspid,
        projectName: biddingProjects.projNm,
        projectType: biddingProjects.pjtType, // 프로젝트 타입 추가
        status: techSalesRfqs.status,
        totalAmount: techSalesVendorQuotations.totalPrice,
        currency: techSalesVendorQuotations.currency,
        dueDate: techSalesRfqs.dueDate,
        createdAt: techSalesRfqs.createdAt,
        quotationCode: techSalesVendorQuotations.quotationCode,
        submittedAt: techSalesVendorQuotations.submittedAt,
      })
      .from(techSalesVendorQuotations)
      .innerJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id))
      .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id))
      .where(whereCondition)
      .orderBy(desc(techSalesRfqs.createdAt))
      .limit(input.perPage)
      .offset(offset);

    console.log("조회된 데이터:", data.length, "개");

    // 전체 개수 조회
    const totalResult = await db
      .select({ count: sql<number>`count(*)`.as("count") })
      .from(techSalesVendorQuotations)
      .innerJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id))
      .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id))
      .where(whereCondition);

    const total = totalResult[0]?.count || 0;
    const pageCount = Math.ceil(total / input.perPage);

    console.log("기술영업 벤더 RFQ 히스토리 조회 완료", {
      id,
      dataLength: data.length,
      total,
      pageCount
    });

    return { data, pageCount };
  } catch (err) {
    console.error("기술영업 벤더 RFQ 히스토리 조회 오류:", {
      err,
      id,
      stack: err instanceof Error ? err.stack : undefined
    });
    return { data: [], pageCount: 0 };
  }
}

/**
 * 기술영업 벤더 엑셀 import 시 유저 생성 및 담당자 등록
 */
export async function importTechVendorsFromExcel(
  vendors: Array<{
    vendorName: string;
    vendorCode?: string | null;
    email: string;
    taxId: string;
    country?: string | null;
    countryEng?: string | null;
    countryFab?: string | null;
    agentName?: string | null;
    agentPhone?: string | null;
    agentEmail?: string | null;
    address?: string | null;
    phone?: string | null;
    website?: string | null;
    techVendorType: string;
    representativeName?: string | null;
    representativeEmail?: string | null;
    representativePhone?: string | null;
    representativeBirth?: string | null;
    items: string;
    contacts?: Array<{
      contactName: string;
      contactPosition?: string;
      contactEmail: string;
      contactPhone?: string;
      contactCountry?: string | null;
      isPrimary?: boolean;
    }>;
  }>,
) {
  unstable_noStore();

  try {
    console.log("Import 시작 - 벤더 수:", vendors.length);
    console.log("첫 번째 벤더 데이터:", vendors[0]);

    const result = await db.transaction(async (tx) => {
      const createdVendors = [];
      const skippedVendors = [];
      const errors = [];

      for (const vendor of vendors) {
        console.log("벤더 처리 시작:", vendor.vendorName);
        
        try {
          // 0. 이메일 타입 검사
          // - 문자열이 아니거나, '@' 미포함, 혹은 객체(예: 하이퍼링크 등)인 경우 모두 거절
          const isEmailString = typeof vendor.email === "string";
          const isEmailContainsAt = isEmailString && vendor.email.includes("@");
          // 하이퍼링크 등 객체로 넘어온 경우 (예: { href: "...", ... } 등) 방지
          const isEmailPlainString = isEmailString && Object.prototype.toString.call(vendor.email) === "[object String]";

          if (!isEmailPlainString || !isEmailContainsAt) {
            console.log("이메일 형식이 올바르지 않습니다:", vendor.email);
            errors.push({
              vendorName: vendor.vendorName,
              email: vendor.email,
              error: "이메일 형식이 올바르지 않습니다"
            });
            continue;
          }

          // 1. 이메일로 기존 벤더 중복 체크
          let existingVendor = await tx.query.techVendors.findFirst({
            where: eq(techVendors.email, vendor.email),
            columns: { id: true, vendorName: true, vendorCode: true, email: true }
          });

          // 2. 이메일이 중복되지 않은 경우 벤더 코드나 이름으로 추가 확인
          if (!existingVendor && vendor.vendorCode) {
            existingVendor = await tx.query.techVendors.findFirst({
              where: eq(techVendors.vendorCode, vendor.vendorCode),
              columns: { id: true, vendorName: true, vendorCode: true, email: true }
            });
          }

          // 3. 벤더 코드도 일치하지 않는 경우 벤더 이름으로 확인
          if (!existingVendor) {
            existingVendor = await tx.query.techVendors.findFirst({
              where: eq(techVendors.vendorName, vendor.vendorName),
              columns: { id: true, vendorName: true, vendorCode: true, email: true }
            });
          }

          // 4. 일치하는 벤더가 있는 경우 처리
          if (existingVendor) {
            console.log("기존 벤더에 담당자 추가:", existingVendor.vendorName, vendor.email);
            
            // 기존 벤더의 벤더 타입 업데이트 (새로운 타입 추가)
            const existingVendorFull = await tx.query.techVendors.findFirst({
              where: eq(techVendors.id, existingVendor.id),
              columns: { id: true, techVendorType: true }
            });
            
            if (existingVendorFull) {
              const existingTypes = existingVendorFull.techVendorType ? existingVendorFull.techVendorType.split(',').map(t => t.trim()) : [];
              const newType = vendor.techVendorType.trim();
              
              // 새로운 타입이 기존에 없는 경우에만 추가
              if (!existingTypes.includes(newType)) {
                const updatedTypes = [...existingTypes, newType];
                const updatedTypeString = updatedTypes.join(', ');
                
                await tx.update(techVendors)
                  .set({ techVendorType: updatedTypeString })
                  .where(eq(techVendors.id, existingVendor.id));
                
                console.log(`벤더 타입 업데이트: ${existingVendorFull.techVendorType} -> ${updatedTypeString}`);
              }
            }

            // 담당자 정보를 기존 벤더에 추가
            let contactName = vendor.vendorName;
            let contactEmail = vendor.email;

            // vendor.contacts가 있고, contactName이 있으면 contactName 사용
            if (vendor.contacts && vendor.contacts.length > 0 && vendor.contacts[0].contactName) {
              contactName = vendor.contacts[0].contactName;
              // 만약 contactEmail이 있으면 그걸 사용, 없으면 vendor.email 사용
              if (vendor.contacts[0].contactEmail) {
                contactEmail = vendor.contacts[0].contactEmail;
              }
            }

            // 담당자 이메일 중복 체크
            const existingContact = await tx.query.techVendorContacts.findFirst({
              where: and(
                eq(techVendorContacts.vendorId, existingVendor.id),
                eq(techVendorContacts.contactEmail, contactEmail)
              ),
              columns: { id: true, contactEmail: true }
            });

            if (existingContact) {
              console.log("담당자 이메일 중복:", contactEmail);
              errors.push({
                vendorName: vendor.vendorName,
                email: vendor.email,
                error: `담당자 이메일 '${contactEmail}'이(가) 이미 등록되어 있습니다`
              });
            } else {
              // 담당자 생성
              await tx.insert(techVendorContacts).values({
                vendorId: existingVendor.id,
                contactName: contactName,
                contactPosition: null,
                contactEmail: contactEmail,
                contactPhone: null,
                contactCountry: null,
                isPrimary: false,
              });
              console.log("담당자 추가 성공:", contactName, contactEmail);
            }

            // 기존 벤더에 담당자 추가했으므로 벤더 생성은 스킵하고 유저 생성으로 넘어감
            skippedVendors.push({
              vendorName: vendor.vendorName,
              email: vendor.email,
              reason: `기존 벤더에 담당자 추가됨 (기존 업체: ${existingVendor.vendorName})`
            });

            // 유저 생성 (기존 벤더의 담당자로 추가된 경우)
            if (contactEmail) {
              console.log("유저 생성 시도:", contactEmail);

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

              if (!existingUser) {
                // 유저가 존재하지 않는 경우 생성
                await tx.insert(users).values({
                  name: contactName,
                  email: contactEmail,
                  techCompanyId: existingVendor.id,
                  domain: "partners",
                });
                console.log("유저 생성 성공");
              } else {
                // 이미 존재하는 유저라면 techCompanyId 업데이트
                await tx.update(users)
                  .set({ techCompanyId: existingVendor.id })
                  .where(eq(users.id, existingUser.id));
                console.log("이미 존재하는 유저, techCompanyId 업데이트:", existingUser.id);
              }
            }

            continue; // 벤더 생성 부분으로 넘어가지 않음
          }

          // 2. 벤더 생성
          const [newVendor] = await tx.insert(techVendors).values({
            vendorName: vendor.vendorName,
            vendorCode: vendor.vendorCode || null,
            taxId: vendor.taxId,
            country: vendor.country || null,
            countryEng: vendor.countryEng || null,
            countryFab: vendor.countryFab || null,
            agentName: vendor.agentName || null,
            agentPhone: vendor.agentPhone || null,
            agentEmail: vendor.agentEmail || null,
            address: vendor.address || null,
            phone: vendor.phone || null,
            email: vendor.email,
            website: vendor.website || null,
            techVendorType: vendor.techVendorType,
            status: "ACTIVE",
            representativeName: vendor.representativeName || null,
            representativeEmail: vendor.representativeEmail || null,
            representativePhone: vendor.representativePhone || null,
            representativeBirth: vendor.representativeBirth || null,
          }).returning();

          console.log("벤더 생성 성공:", newVendor.id);

          // 2. 담당자 생성 (최소 1명 이상 등록)
          if (vendor.contacts && vendor.contacts.length > 0) {
            console.log("담당자 생성 시도:", vendor.contacts.length, "명");
            
            for (const contact of vendor.contacts) {
              await tx.insert(techVendorContacts).values({
                vendorId: newVendor.id,
                contactName: contact.contactName,
                contactPosition: contact.contactPosition || null,
                contactEmail: contact.contactEmail,
                contactPhone: contact.contactPhone || null,
                contactCountry: contact.contactCountry || null,
                isPrimary: contact.isPrimary || false,
              });
              console.log("담당자 생성 성공:", contact.contactName, contact.contactEmail);
            }
          } 
          else {
            // 담당자 정보가 없는 경우 벤더 정보로 기본 담당자 생성
            console.log("기본 담당자 생성");
            await tx.insert(techVendorContacts).values({
              vendorId: newVendor.id,
              contactName: vendor.representativeName || vendor.vendorName || "기본 담당자",
              contactPosition: null,
              contactEmail: vendor.email,
              contactPhone: vendor.representativePhone || vendor.phone || null,
              contactCountry: vendor.country || null,
              isPrimary: true,
            });
            console.log("기본 담당자 생성 성공:", vendor.email);
          }

          // 3. 유저 생성 (이메일이 있는 경우)
          if (vendor.email) {
            console.log("유저 생성 시도:", vendor.email);

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

            if (!existingUser) {
              // 유저가 존재하지 않는 경우 생성
              await tx.insert(users).values({
                name: vendor.vendorName,
                email: vendor.email,
                techCompanyId: newVendor.id,
                domain: "partners",
              });
              console.log("유저 생성 성공");
            } else {
              // 이미 존재하는 유저라면 techCompanyId 업데이트
              await tx.update(users)
                .set({ techCompanyId: newVendor.id })
                .where(eq(users.id, existingUser.id));
              console.log("이미 존재하는 유저, techCompanyId 업데이트:", existingUser.id);
            }
          }

          createdVendors.push(newVendor);
          console.log("벤더 처리 완료:", vendor.vendorName);
        } catch (error) {
          console.error("벤더 처리 중 오류 발생:", vendor.vendorName, error);
          errors.push({
            vendorName: vendor.vendorName,
            email: vendor.email,
            error: error instanceof Error ? error.message : "알 수 없는 오류"
          });
          // 개별 벤더 오류는 전체 트랜잭션을 롤백하지 않도록 continue
          continue;
        }
      }

      console.log("모든 벤더 처리 완료:", {
        생성됨: createdVendors.length,
        스킵됨: skippedVendors.length,
        오류: errors.length
      });
      
      return { 
        createdVendors, 
        skippedVendors, 
        errors,
        totalProcessed: vendors.length,
        successCount: createdVendors.length,
        skipCount: skippedVendors.length,
        errorCount: errors.length
      };
    });

    // 캐시 무효화
    revalidateTag("tech-vendors");
    revalidateTag("tech-vendor-contacts");
    revalidateTag("users");

    console.log("Import 완료 - 결과:", result);
    
    // 결과 메시지 생성
    const messages = [];
    if (result.successCount > 0) {
      messages.push(`${result.successCount}개 벤더 생성 성공`);
    }
    if (result.skipCount > 0) {
      messages.push(`${result.skipCount}개 벤더 중복으로 스킵`);
    }
    if (result.errorCount > 0) {
      messages.push(`${result.errorCount}개 벤더 처리 중 오류`);
    }
    
    return { 
      success: true, 
      data: result,
      message: messages.join(", "),
      details: {
        created: result.createdVendors,
        skipped: result.skippedVendors,
        errors: result.errors
      }
    };
  } catch (error) {
    console.error("Import 실패:", error);
    return { success: false, error: getErrorMessage(error) };
  }
}

export async function findTechVendorById(id: number): Promise<TechVendor | null> {
  const result = await db
    .select()
    .from(techVendors)
    .where(eq(techVendors.id, id))
    .limit(1)

  return result[0] || null
}

/**
 * 회원가입 폼을 통한 기술영업 벤더 생성 (초대 토큰 기반)
 */
export async function createTechVendorFromSignup(params: {
  vendorData: {
    vendorName: string
    vendorCode?: string
    items: string
    website?: string
    taxId: string
    address?: string
    email: string
    phone?: string
    country: string
    techVendorType: "조선" | "해양TOP" | "해양HULL" | ("조선" | "해양TOP" | "해양HULL")[]
    representativeName?: string
    representativeBirth?: string
    representativeEmail?: string
    representativePhone?: string
  }
  files?: File[]
  contacts: {
    contactName: string
    contactPosition?: string
    contactEmail: string
    contactPhone?: string
    isPrimary?: boolean
  }[]
  selectedItemCodes?: string[] // 선택된 아이템 코드들
  invitationToken?: string // 초대 토큰
}) {
  unstable_noStore();

  try {
    console.log("기술영업 벤더 회원가입 시작:", params.vendorData.vendorName);

    // 초대 토큰 검증
    let existingVendorId: number | null = null;
    if (params.invitationToken) {
      const { verifyTechVendorInvitationToken } = await import("@/lib/tech-vendor-invitation-token");
      const tokenPayload = await verifyTechVendorInvitationToken(params.invitationToken);
      
      if (!tokenPayload) {
        throw new Error("유효하지 않은 초대 토큰입니다.");
      }
      
      existingVendorId = tokenPayload.vendorId;
      console.log("초대 토큰 검증 성공, 벤더 ID:", existingVendorId);
    }

    const result = await db.transaction(async (tx) => {
      let vendorResult;
      
      if (existingVendorId) {
        // 기존 벤더 정보 업데이트
        const [updatedVendor] = await tx.update(techVendors)
          .set({
            vendorName: params.vendorData.vendorName,
            vendorCode: params.vendorData.vendorCode || null,
            taxId: params.vendorData.taxId,
            country: params.vendorData.country,
            address: params.vendorData.address || null,
            phone: params.vendorData.phone || null,
            email: params.vendorData.email,
            website: params.vendorData.website || null,
            techVendorType: Array.isArray(params.vendorData.techVendorType) 
              ? params.vendorData.techVendorType[0] 
              : params.vendorData.techVendorType,
            status: "QUOTE_COMPARISON", // 가입 완료 시 QUOTE_COMPARISON으로 변경
            representativeName: params.vendorData.representativeName || null,
            representativeEmail: params.vendorData.representativeEmail || null,
            representativePhone: params.vendorData.representativePhone || null,
            representativeBirth: params.vendorData.representativeBirth || null,
            items: params.vendorData.items,
            updatedAt: new Date(),
          })
          .where(eq(techVendors.id, existingVendorId))
          .returning();
        
        vendorResult = updatedVendor;
        console.log("기존 벤더 정보 업데이트 완료:", vendorResult.id);
      } else {
        // 1. 이메일 중복 체크 (새 벤더인 경우)
        const existingVendor = await tx.query.techVendors.findFirst({
          where: eq(techVendors.email, params.vendorData.email),
          columns: { id: true, vendorName: true }
        });

        if (existingVendor) {
          throw new Error(`이미 등록된 이메일입니다: ${params.vendorData.email} (기존 업체: ${existingVendor.vendorName})`);
        }

        // 2. 새 벤더 생성
        const [newVendor] = await tx.insert(techVendors).values({
          vendorName: params.vendorData.vendorName,
          vendorCode: params.vendorData.vendorCode || null,
          taxId: params.vendorData.taxId,
          country: params.vendorData.country,
          address: params.vendorData.address || null,
          phone: params.vendorData.phone || null,
          email: params.vendorData.email,
          website: params.vendorData.website || null,
          techVendorType: Array.isArray(params.vendorData.techVendorType) 
            ? params.vendorData.techVendorType[0] 
            : params.vendorData.techVendorType,
          status: "QUOTE_COMPARISON",
          isQuoteComparison: false,
          representativeName: params.vendorData.representativeName || null,
          representativeEmail: params.vendorData.representativeEmail || null,
          representativePhone: params.vendorData.representativePhone || null,
          representativeBirth: params.vendorData.representativeBirth || null,
          items: params.vendorData.items,
        }).returning();

        vendorResult = newVendor;
        console.log("새 벤더 생성 완료:", vendorResult.id);
      }

      // 이 부분은 위에서 이미 처리되었으므로 주석 처리

      // 3. 연락처 생성
      if (params.contacts && params.contacts.length > 0) {
        for (const [index, contact] of params.contacts.entries()) {
          await tx.insert(techVendorContacts).values({
            vendorId: vendorResult.id,
            contactName: contact.contactName,
            contactPosition: contact.contactPosition || null,
            contactEmail: contact.contactEmail,
            contactPhone: contact.contactPhone || null,
            isPrimary: index === 0, // 첫 번째 연락처를 primary로 설정
          });
        }
        console.log("연락처 생성 완료:", params.contacts.length, "개");
      }

      // 4. 선택된 아이템들을 tech_vendor_possible_items에 저장
      if (params.selectedItemCodes && params.selectedItemCodes.length > 0) {
        for (const itemCode of params.selectedItemCodes) {
          // 아이템 코드로 각 테이블에서 찾기
          let itemId = null;
          let itemType = null;
          
          // 조선 아이템에서 찾기
          const shipbuildingItem = await tx.query.itemShipbuilding.findFirst({
            where: eq(itemShipbuilding.itemCode, itemCode)
          });
          if (shipbuildingItem) {
            itemId = shipbuildingItem.id;
            itemType = "SHIP";
          } else {
            // 해양 TOP 아이템에서 찾기
            const offshoreTopItem = await tx.query.itemOffshoreTop.findFirst({
              where: eq(itemOffshoreTop.itemCode, itemCode)
            });
            if (offshoreTopItem) {
              itemId = offshoreTopItem.id;
              itemType = "TOP";
            } else {
              // 해양 HULL 아이템에서 찾기
              const offshoreHullItem = await tx.query.itemOffshoreHull.findFirst({
                where: eq(itemOffshoreHull.itemCode, itemCode)
              });
              if (offshoreHullItem) {
                itemId = offshoreHullItem.id;
                itemType = "HULL";
              }
            }
          }
          
          if (itemId && itemType) {
            // 중복 체크
            // let existingItem;
            const whereConditions = [eq(techVendorPossibleItems.vendorId, vendorResult.id)];
            
            if (itemType === "SHIP") {
              whereConditions.push(eq(techVendorPossibleItems.shipbuildingItemId, itemId));
            } else if (itemType === "TOP") {
              whereConditions.push(eq(techVendorPossibleItems.offshoreTopItemId, itemId));
            } else if (itemType === "HULL") {
              whereConditions.push(eq(techVendorPossibleItems.offshoreHullItemId, itemId));
            }
            
            const existingItem = await tx.query.techVendorPossibleItems.findFirst({
              where: and(...whereConditions)
            });
            
            if (!existingItem) {
              // 새 아이템 추가
              const insertData: {
                vendorId: number;
                shipbuildingItemId?: number;
                offshoreTopItemId?: number;
                offshoreHullItemId?: number;
              } = {
                vendorId: vendorResult.id,
              };
              
              if (itemType === "SHIP") {
                insertData.shipbuildingItemId = itemId;
              } else if (itemType === "TOP") {
                insertData.offshoreTopItemId = itemId;
              } else if (itemType === "HULL") {
                insertData.offshoreHullItemId = itemId;
              }
              
              await tx.insert(techVendorPossibleItems).values(insertData);
            }
          }
        }
        console.log("선택된 아이템 저장 완료:", params.selectedItemCodes.length, "개");
      }

      // 4. 첨부파일 처리
      if (params.files && params.files.length > 0) {
        await storeTechVendorFiles(tx, vendorResult.id, params.files, "GENERAL");
        console.log("첨부파일 저장 완료:", params.files.length, "개");
      }

      // 5. 유저 생성 (techCompanyId 설정)
      console.log("유저 생성 시도:", params.vendorData.email);
      
      const existingUser = await tx.query.users.findFirst({
        where: eq(users.email, params.vendorData.email),
        columns: { id: true, techCompanyId: true }
      });

      let userId = null;
      if (!existingUser) {
        const [newUser] = await tx.insert(users).values({
          name: params.vendorData.vendorName,
          email: params.vendorData.email,
          techCompanyId: vendorResult.id, // 중요: techCompanyId 설정
          domain: "partners",
        }).returning();
        userId = newUser.id;
        console.log("유저 생성 성공:", userId);
      } else {
        // 기존 유저의 techCompanyId 업데이트
        if (!existingUser.techCompanyId) {
          await tx.update(users)
            .set({ techCompanyId: vendorResult.id })
            .where(eq(users.id, existingUser.id));
          console.log("기존 유저의 techCompanyId 업데이트:", existingUser.id);
        }
        userId = existingUser.id;
      }

      return { vendor: vendorResult, userId };
    });

    // 캐시 무효화
    revalidateTag("tech-vendors");
    revalidateTag("tech-vendor-possible-items");
    revalidateTag("users");

    console.log("기술영업 벤더 회원가입 완료:", result);
    return { success: true, data: result };
  } catch (error) {
    console.error("기술영업 벤더 회원가입 실패:", error);
    return { success: false, error: getErrorMessage(error) };
  }
}

/**
 * 단일 기술영업 벤더 추가 (사용자 계정도 함께 생성)
 */
export async function addTechVendor(input: {
  vendorName: string;
  vendorCode?: string | null;
  email: string;
  taxId: string;
  country?: string | null;
  countryEng?: string | null;
  countryFab?: string | null;
  agentName?: string | null;
  agentPhone?: string | null;
  agentEmail?: string | null;
  address?: string | null;
  phone?: string | null;
  website?: string | null;
  techVendorType: string;
  representativeName?: string | null;
  representativeEmail?: string | null;
  representativePhone?: string | null;
  representativeBirth?: string | null;
  isQuoteComparison?: boolean;
}) {
  unstable_noStore();

  try {
    console.log("벤더 추가 시작:", input.vendorName);

    const result = await db.transaction(async (tx) => {
      // 1. 이메일 중복 체크
      const existingVendor = await tx.query.techVendors.findFirst({
        where: eq(techVendors.email, input.email),
        columns: { id: true, vendorName: true }
      });

      if (existingVendor) {
        throw new Error(`이미 등록된 이메일입니다: ${input.email} (업체명: ${existingVendor.vendorName})`);
      }

      // 2. 벤더 생성
      console.log("벤더 생성 시도:", {
        vendorName: input.vendorName,
        email: input.email,
        techVendorType: input.techVendorType
      });

      const [newVendor] = await tx.insert(techVendors).values({
        vendorName: input.vendorName,
        vendorCode: input.vendorCode || null,
        taxId: input.taxId || null,
        country: input.country || null,
        countryEng: input.countryEng || null,
        countryFab: input.countryFab || null,
        agentName: input.agentName || null,
        agentPhone: input.agentPhone || null,
        agentEmail: input.agentEmail || null,
        address: input.address || null,
        phone: input.phone || null,
        email: input.email,
        website: input.website || null,
        techVendorType: Array.isArray(input.techVendorType) ? input.techVendorType.join(',') : input.techVendorType,
        status: input.isQuoteComparison ? "PENDING_INVITE" : "ACTIVE",
        isQuoteComparison: input.isQuoteComparison || false,
        representativeName: input.representativeName || null,
        representativeEmail: input.representativeEmail || null,
        representativePhone: input.representativePhone || null,
        representativeBirth: input.representativeBirth || null,
      }).returning();

      console.log("벤더 생성 성공:", newVendor.id);

      // 3. 견적비교용 벤더인 경우 PENDING_REVIEW 상태로 생성됨
      // 초대는 별도의 초대 버튼을 통해 진행
      console.log("벤더 생성 완료:", newVendor.id, "상태:", newVendor.status);

      // 4. 견적비교용 벤더(isQuoteComparison)가 아닌 경우에만 유저 생성
      let userId = null;
      if (!input.isQuoteComparison) {
        console.log("유저 생성 시도:", input.email);

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

        // 유저가 존재하지 않는 경우에만 생성
        if (!existingUser) {
          const [newUser] = await tx.insert(users).values({
            name: input.vendorName,
            email: input.email,
            techCompanyId: newVendor.id, // techCompanyId 설정
            domain: "partners",
          }).returning();
          userId = newUser.id;
          console.log("유저 생성 성공:", userId);
        } else {
          // 이미 존재하는 유저의 techCompanyId가 null인 경우 업데이트
          if (!existingUser.techCompanyId) {
            await tx.update(users)
              .set({ techCompanyId: newVendor.id })
              .where(eq(users.id, existingUser.id));
            console.log("기존 유저의 techCompanyId 업데이트:", existingUser.id);
          }
          userId = existingUser.id;
          console.log("이미 존재하는 유저:", userId);
        }
      } else {
        console.log("견적비교용 벤더이므로 유저를 생성하지 않습니다.");
      }

      return { vendor: newVendor, userId };
    });

    // 캐시 무효화
    revalidateTag("tech-vendors");
    revalidateTag("users");

    console.log("벤더 추가 완료:", result);
    return { success: true, data: result };
  } catch (error) {
    console.error("벤더 추가 실패:", error);
    return { success: false, error: getErrorMessage(error) };
  }
}

/**
 * 벤더의 possible items 개수 조회
 */
export async function getTechVendorPossibleItemsCount(vendorId: number): Promise<number> {
  try {
    const result = await db
      .select({ count: sql<number>`count(*)`.as("count") })
      .from(techVendorPossibleItems)
      .where(eq(techVendorPossibleItems.vendorId, vendorId));
    
    return result[0]?.count || 0;
  } catch (err) {
    console.error("Error getting tech vendor possible items count:", err);
    return 0;
  }
}

/**
 * 기술영업 벤더 초대 메일 발송
 */
export async function inviteTechVendor(params: {
  vendorId: number;
  subject: string;
  message: string;
  recipientEmail: string;
}) {
  unstable_noStore();

  try {
    console.log("기술영업 벤더 초대 메일 발송 시작:", params.vendorId);

    const result = await db.transaction(async (tx) => {
      // 벤더 정보 조회
      const vendor = await tx.query.techVendors.findFirst({
        where: eq(techVendors.id, params.vendorId),
      });

      if (!vendor) {
        throw new Error("벤더를 찾을 수 없습니다.");
      }

      // 벤더 상태를 INVITED로 변경 (PENDING_INVITE에서)
      if (vendor.status !== "PENDING_INVITE") {
        throw new Error("초대 가능한 상태가 아닙니다. (PENDING_INVITE 상태만 초대 가능)");
      }

      await tx.update(techVendors)
        .set({ 
          status: "INVITED",
          updatedAt: new Date(),
        })
        .where(eq(techVendors.id, params.vendorId));

      // 초대 토큰 생성
      const { createTechVendorInvitationToken, createTechVendorSignupUrl } = await import("@/lib/tech-vendor-invitation-token");
      const { sendEmail } = await import("@/lib/mail/sendEmail");
      
      const invitationToken = await createTechVendorInvitationToken({
        vendorType: vendor.techVendorType as "조선" | "해양TOP" | "해양HULL" | ("조선" | "해양TOP" | "해양HULL")[],
        vendorId: vendor.id,
        vendorName: vendor.vendorName,
        email: params.recipientEmail,
      });
      
      const signupUrl = await createTechVendorSignupUrl(invitationToken);
      
      // 초대 메일 발송
      await sendEmail({
        to: params.recipientEmail,
        subject: params.subject,
        template: "tech-vendor-invitation",
        context: {
          companyName: vendor.vendorName,
          language: "ko",
          registrationLink: signupUrl,
          customMessage: params.message,
        }
      });
      
      console.log("초대 메일 발송 완료:", params.recipientEmail);
      
      return { vendor, invitationToken, signupUrl };
    });

    // 캐시 무효화
    revalidateTag("tech-vendors");

    console.log("기술영업 벤더 초대 완료:", result);
    return { success: true, data: result };
  } catch (error) {
    console.error("기술영업 벤더 초대 실패:", error);
    return { success: false, error: getErrorMessage(error) };
  }
}

/* -----------------------------------------------------
   Possible Items 관련 함수들
----------------------------------------------------- */

/**
 * 특정 벤더의 possible items 조회 (페이지네이션 포함) - 새 스키마에 맞게 수정
 */
export async function getTechVendorPossibleItems(input: GetTechVendorPossibleItemsSchema, vendorId: number) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage

        // 벤더 ID 조건
        const vendorWhere = eq(techVendorPossibleItems.vendorId, vendorId)

        // 조선 아이템들 조회
        const shipItems = await db
          .select({
            id: techVendorPossibleItems.id,
            vendorId: techVendorPossibleItems.vendorId,
            shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
            offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
            offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
            createdAt: techVendorPossibleItems.createdAt,
            updatedAt: techVendorPossibleItems.updatedAt,
            itemCode: itemShipbuilding.itemCode,
            workType: itemShipbuilding.workType,
            itemList: itemShipbuilding.itemList,
            shipTypes: itemShipbuilding.shipTypes,
            subItemList: sql<string>`null`.as("subItemList"),
            techVendorType: techVendors.techVendorType,
          })
          .from(techVendorPossibleItems)
          .leftJoin(itemShipbuilding, eq(techVendorPossibleItems.shipbuildingItemId, itemShipbuilding.id))
          .leftJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .where(and(vendorWhere, not(isNull(techVendorPossibleItems.shipbuildingItemId))))

        // 해양 TOP 아이템들 조회
        const topItems = await db
          .select({
            id: techVendorPossibleItems.id,
            vendorId: techVendorPossibleItems.vendorId,
            shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
            offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
            offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
            createdAt: techVendorPossibleItems.createdAt,
            updatedAt: techVendorPossibleItems.updatedAt,
            itemCode: itemOffshoreTop.itemCode,
            workType: itemOffshoreTop.workType,
            itemList: itemOffshoreTop.itemList,
            shipTypes: sql<string>`null`.as("shipTypes"),
            subItemList: itemOffshoreTop.subItemList,
            techVendorType: techVendors.techVendorType,
          })
          .from(techVendorPossibleItems)
          .leftJoin(itemOffshoreTop, eq(techVendorPossibleItems.offshoreTopItemId, itemOffshoreTop.id))
          .leftJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .where(and(vendorWhere, not(isNull(techVendorPossibleItems.offshoreTopItemId))))

        // 해양 HULL 아이템들 조회
        const hullItems = await db
          .select({
            id: techVendorPossibleItems.id,
            vendorId: techVendorPossibleItems.vendorId,
            shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
            offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
            offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
            createdAt: techVendorPossibleItems.createdAt,
            updatedAt: techVendorPossibleItems.updatedAt,
            itemCode: itemOffshoreHull.itemCode,
            workType: itemOffshoreHull.workType,
            itemList: itemOffshoreHull.itemList,
            shipTypes: sql<string>`null`.as("shipTypes"),
            subItemList: itemOffshoreHull.subItemList,
            techVendorType: techVendors.techVendorType,
          })
          .from(techVendorPossibleItems)
          .leftJoin(itemOffshoreHull, eq(techVendorPossibleItems.offshoreHullItemId, itemOffshoreHull.id))
          .leftJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .where(and(vendorWhere, not(isNull(techVendorPossibleItems.offshoreHullItemId))))

        // 모든 아이템들 합치기
        const allItems = [...shipItems, ...topItems, ...hullItems]

        // 필터링 적용
        let filteredItems = allItems

        if (input.search) {
          const s = input.search.toLowerCase()
          filteredItems = filteredItems.filter(item => 
            item.itemCode?.toLowerCase().includes(s) ||
            item.workType?.toLowerCase().includes(s) ||
            item.itemList?.toLowerCase().includes(s) ||
            item.shipTypes?.toLowerCase().includes(s) ||
            item.subItemList?.toLowerCase().includes(s)
          )
        }

        if (input.itemCode) {
          filteredItems = filteredItems.filter(item => 
            item.itemCode?.toLowerCase().includes(input.itemCode!.toLowerCase())
          )
        }

        if (input.workType) {
          filteredItems = filteredItems.filter(item => 
            item.workType?.toLowerCase().includes(input.workType!.toLowerCase())
          )
        }

        if (input.itemList) {
          filteredItems = filteredItems.filter(item => 
            item.itemList?.toLowerCase().includes(input.itemList!.toLowerCase())
          )
        }

        if (input.shipTypes) {
          filteredItems = filteredItems.filter(item => 
            item.shipTypes?.toLowerCase().includes(input.shipTypes!.toLowerCase())
          )
        }

        if (input.subItemList) {
          filteredItems = filteredItems.filter(item => 
            item.subItemList?.toLowerCase().includes(input.subItemList!.toLowerCase())
          )
        }

        // 정렬
        if (input.sort.length > 0) {
          filteredItems.sort((a, b) => {
            for (const sortItem of input.sort) {
              let aVal = (a as any)[sortItem.id]
              let bVal = (b as any)[sortItem.id]
              
              if (aVal === null || aVal === undefined) aVal = ""
              if (bVal === null || bVal === undefined) bVal = ""
              
              if (aVal < bVal) return sortItem.desc ? 1 : -1
              if (aVal > bVal) return sortItem.desc ? -1 : 1
            }
            return 0
          })
        } else {
          // 기본 정렬: createdAt 내림차순
          filteredItems.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
        }

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

        // 페이지네이션 적용
        const data = filteredItems.slice(offset, offset + input.perPage)

        return { data, pageCount }
      } catch (err) {
        console.error("Error fetching tech vendor possible items:", err)
        return { data: [], pageCount: 0 }
      }
    },
    [JSON.stringify(input), String(vendorId)],
    {
      revalidate: 3600,
      tags: [`tech-vendor-possible-items-${vendorId}`],
    }
  )()
}

export async function createTechVendorPossibleItemNew(input: CreateTechVendorPossibleItemSchema) {
  unstable_noStore()
  
  try {
    // 중복 체크 - 새 스키마에 맞게 수정
    let existing = null
    
    if (input.shipbuildingItemId) {
      existing = await db
        .select({ id: techVendorPossibleItems.id })
        .from(techVendorPossibleItems)
        .where(
          and(
            eq(techVendorPossibleItems.vendorId, input.vendorId),
            eq(techVendorPossibleItems.shipbuildingItemId, input.shipbuildingItemId)
          )
        )
        .limit(1)
    } else if (input.offshoreTopItemId) {
      existing = await db
        .select({ id: techVendorPossibleItems.id })
        .from(techVendorPossibleItems)
        .where(
          and(
            eq(techVendorPossibleItems.vendorId, input.vendorId),
            eq(techVendorPossibleItems.offshoreTopItemId, input.offshoreTopItemId)
          )
        )
        .limit(1)
    } else if (input.offshoreHullItemId) {
      existing = await db
        .select({ id: techVendorPossibleItems.id })
        .from(techVendorPossibleItems)
        .where(
          and(
            eq(techVendorPossibleItems.vendorId, input.vendorId),
            eq(techVendorPossibleItems.offshoreHullItemId, input.offshoreHullItemId)
          )
        )
        .limit(1)
    }

    if (existing && existing.length > 0) {
      return { data: null, error: "이미 등록된 아이템입니다." }
    }

    const [newItem] = await db
      .insert(techVendorPossibleItems)
      .values({
        vendorId: input.vendorId,
        shipbuildingItemId: input.shipbuildingItemId || null,
        offshoreTopItemId: input.offshoreTopItemId || null,
        offshoreHullItemId: input.offshoreHullItemId || null,
      })
      .returning()

    revalidateTag(`tech-vendor-possible-items-${input.vendorId}`)
    return { data: newItem, error: null }
  } catch (err) {
    console.error("Error creating tech vendor possible item:", err)
    return { data: null, error: getErrorMessage(err) }
  }
}

export async function deleteTechVendorPossibleItemsNew(ids: number[], vendorId: number) {
  unstable_noStore()
  
  try {
    await db
      .delete(techVendorPossibleItems)
      .where(inArray(techVendorPossibleItems.id, ids))

    revalidateTag(`tech-vendor-possible-items-${vendorId}`)
    return { data: null, error: null }
  } catch (err) {
    return { data: null, error: getErrorMessage(err) }
  }
}

export async function addTechVendorPossibleItem(input: {
  vendorId: number;
  itemId: number;
  itemType: "SHIP" | "TOP" | "HULL";
}) {
  unstable_noStore();
  try {
    // 중복 체크
    // let existingItem;
    const whereConditions = [eq(techVendorPossibleItems.vendorId, input.vendorId)];
    
    if (input.itemType === "SHIP") {
      whereConditions.push(eq(techVendorPossibleItems.shipbuildingItemId, input.itemId));
    } else if (input.itemType === "TOP") {
      whereConditions.push(eq(techVendorPossibleItems.offshoreTopItemId, input.itemId));
    } else if (input.itemType === "HULL") {
      whereConditions.push(eq(techVendorPossibleItems.offshoreHullItemId, input.itemId));
    }
    
    const existingItem = await db.query.techVendorPossibleItems.findFirst({
      where: and(...whereConditions)
    });

    if (existingItem) {
      return { success: false, error: "이미 추가된 아이템입니다." };
    }

    // 새 아이템 추가
    const insertData: {
      vendorId: number;
      shipbuildingItemId?: number;
      offshoreTopItemId?: number;
      offshoreHullItemId?: number;
    } = {
      vendorId: input.vendorId,
    };

    if (input.itemType === "SHIP") {
      insertData.shipbuildingItemId = input.itemId;
    } else if (input.itemType === "TOP") {
      insertData.offshoreTopItemId = input.itemId;
    } else if (input.itemType === "HULL") {
      insertData.offshoreHullItemId = input.itemId;
    }

    const [newItem] = await db
      .insert(techVendorPossibleItems)
      .values(insertData)
      .returning();

    revalidateTag(`tech-vendor-possible-items-${input.vendorId}`);
    
    return { success: true, data: newItem };
  } catch (err) {
    return { success: false, error: getErrorMessage(err) };
  }
}

/**
 * 아이템 추가 시 중복 체크 함수
 * 조선의 경우 아이템코드+선종 조합으로, 나머지는 아이템코드만으로 중복 체크
 */
export async function checkTechVendorItemDuplicate(
  vendorId: number,
  itemType: "SHIP" | "TOP" | "HULL",
  itemCode: string,
  shipTypes?: string
) {
  try {
    if (itemType === "SHIP") {
      // 조선의 경우 아이템코드 + 선종 조합으로 중복 체크
      const shipItem = await db
        .select({ id: itemShipbuilding.id })
        .from(itemShipbuilding)
        .where(
          and(
            eq(itemShipbuilding.itemCode, itemCode),
            shipTypes ? eq(itemShipbuilding.shipTypes, shipTypes) : isNull(itemShipbuilding.shipTypes)
          )
        )
        .limit(1)

      if (!shipItem.length) {
        return { isDuplicate: false, error: null }
      }

      const existing = await db
        .select({ id: techVendorPossibleItems.id })
        .from(techVendorPossibleItems)
        .where(
          and(
            eq(techVendorPossibleItems.vendorId, vendorId),
            eq(techVendorPossibleItems.shipbuildingItemId, shipItem[0].id)
          )
        )
        .limit(1)

      if (existing.length > 0) {
        return { 
          isDuplicate: true, 
          error: "이미 사용중인 아이템 코드 및 선종 입니다"
        }
      }
    } else if (itemType === "TOP") {
      // 해양 TOP의 경우 아이템코드만으로 중복 체크
      const topItem = await db
        .select({ id: itemOffshoreTop.id })
        .from(itemOffshoreTop)
        .where(eq(itemOffshoreTop.itemCode, itemCode))
        .limit(1)

      if (!topItem.length) {
        return { isDuplicate: false, error: null }
      }

      const existing = await db
        .select({ id: techVendorPossibleItems.id })
        .from(techVendorPossibleItems)
        .where(
          and(
            eq(techVendorPossibleItems.vendorId, vendorId),
            eq(techVendorPossibleItems.offshoreTopItemId, topItem[0].id)
          )
        )
        .limit(1)

      if (existing.length > 0) {
        return { 
          isDuplicate: true, 
          error: "이미 사용중인 아이템 코드 입니다"
        }
      }
    } else if (itemType === "HULL") {
      // 해양 HULL의 경우 아이템코드만으로 중복 체크
      const hullItem = await db
        .select({ id: itemOffshoreHull.id })
        .from(itemOffshoreHull)
        .where(eq(itemOffshoreHull.itemCode, itemCode))
        .limit(1)

      if (!hullItem.length) {
        return { isDuplicate: false, error: null }
      }

      const existing = await db
        .select({ id: techVendorPossibleItems.id })
        .from(techVendorPossibleItems)
        .where(
          and(
            eq(techVendorPossibleItems.vendorId, vendorId),
            eq(techVendorPossibleItems.offshoreHullItemId, hullItem[0].id)
          )
        )
        .limit(1)

      if (existing.length > 0) {
        return { 
          isDuplicate: true, 
          error: "이미 사용중인 아이템 코드 입니다"
        }
      }
    }

    return { isDuplicate: false, error: null }
  } catch (err) {
    console.error("Error checking duplicate:", err)
    return { isDuplicate: false, error: getErrorMessage(err) }
  }
}

export async function deleteTechVendorPossibleItem(itemId: number, vendorId: number) {
  unstable_noStore();
  try {
    const [deletedItem] = await db
      .delete(techVendorPossibleItems)
      .where(eq(techVendorPossibleItems.id, itemId))
      .returning();

    revalidateTag(`tech-vendor-possible-items-${vendorId}`);
    
    return { success: true, data: deletedItem };
  } catch (err) {
    return { success: false, error: getErrorMessage(err) };
  }
}



//기술영업 담당자 연락처 관련 함수들

export interface ImportContactData {
  vendorEmail: string // 벤더 대표이메일 (유니크)
  contactName: string
  contactPosition?: string
  contactEmail: string
  contactPhone?: string
  contactCountry?: string
  isPrimary?: boolean
}

export interface ImportResult {
  success: boolean
  totalRows: number
  successCount: number
  failedRows: Array<{
    row: number
    error: string
    vendorEmail: string
    contactName: string
    contactEmail: string
  }>
}

/**
 * 벤더 대표이메일로 벤더 찾기
 */
async function getTechVendorByEmail(email: string) {
  const vendor = await db
    .select({
      id: techVendors.id,
      vendorName: techVendors.vendorName,
      email: techVendors.email,
    })
    .from(techVendors)
    .where(eq(techVendors.email, email))
    .limit(1)

  return vendor[0] || null
}

/**
 * 연락처 이메일 중복 체크
 */
async function checkContactEmailExists(vendorId: number, contactEmail: string) {
  const existing = await db
    .select()
    .from(techVendorContacts)
    .where(
      and(
        eq(techVendorContacts.vendorId, vendorId),
        eq(techVendorContacts.contactEmail, contactEmail)
      )
    )
    .limit(1)

  return existing.length > 0
}

/**
 * 벤더 연락처 일괄 import
 */
export async function importTechVendorContacts(
  data: ImportContactData[]
): Promise<ImportResult> {
  const result: ImportResult = {
    success: true,
    totalRows: data.length,
    successCount: 0,
    failedRows: [],
  }

  for (let i = 0; i < data.length; i++) {
    const row = data[i]
    const rowNumber = i + 1

    try {
      // 1. 벤더 이메일로 벤더 찾기
      if (!row.vendorEmail || !row.vendorEmail.trim()) {
        result.failedRows.push({
          row: rowNumber,
          error: "벤더 대표이메일은 필수입니다.",
          vendorEmail: row.vendorEmail,
          contactName: row.contactName,
          contactEmail: row.contactEmail,
        })
        continue
      }

      const vendor = await getTechVendorByEmail(row.vendorEmail.trim())
      if (!vendor) {
        result.failedRows.push({
          row: rowNumber,
          error: `벤더 대표이메일 '${row.vendorEmail}'을(를) 찾을 수 없습니다.`,
          vendorEmail: row.vendorEmail,
          contactName: row.contactName,
          contactEmail: row.contactEmail,
        })
        continue
      }

      // 2. 연락처 이메일 중복 체크
      const isDuplicate = await checkContactEmailExists(vendor.id, row.contactEmail)
      if (isDuplicate) {
        result.failedRows.push({
          row: rowNumber,
          error: `이미 존재하는 연락처 이메일입니다: ${row.contactEmail}`,
          vendorEmail: row.vendorEmail,
          contactName: row.contactName,
          contactEmail: row.contactEmail,
        })
        continue
      }

      // 3. 연락처 생성
      await db.insert(techVendorContacts).values({
        vendorId: vendor.id,
        contactName: row.contactName || null,
        contactPosition: row.contactPosition || null,
        contactEmail: row.contactEmail,
        contactPhone: row.contactPhone || null,
        contactCountry: row.contactCountry || null,
        isPrimary: row.isPrimary || false,
      })

      result.successCount++
    } catch (error) {
      result.failedRows.push({
        row: rowNumber,
        error: error instanceof Error ? error.message : "알 수 없는 오류",
        vendorEmail: row.vendorEmail,
        contactName: row.contactName,
        contactEmail: row.contactEmail,
      })
    }
  }

  // 캐시 무효화
  revalidateTag("tech-vendor-contacts")

  return result
}

/**
 * 벤더 연락처 import 템플릿 생성
 */
export async function generateContactImportTemplate(): Promise<Blob> {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet("벤더연락처_템플릿")

  // 헤더 설정
  worksheet.columns = [
    { header: "벤더대표이메일*", key: "vendorEmail", width: 25 },
    { header: "담당자명", key: "contactName", width: 20 },
    { header: "직책", key: "contactPosition", width: 15 },
    { header: "담당자이메일*", key: "contactEmail", width: 25 },
    { header: "담당자연락처", key: "contactPhone", width: 15 },
    { header: "담당자국가", key: "contactCountry", width: 15 },
    { header: "주담당자여부", key: "isPrimary", width: 12 },
  ]

  // 헤더 스타일 설정
  const headerRow = worksheet.getRow(1)
  headerRow.font = { bold: true }
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFE0E0E0" },
  }

  // 예시 데이터 추가
  worksheet.addRow({
    vendorEmail: "example@company.com",
    contactName: "홍길동",
    contactPosition: "대표",
    contactEmail: "hong@company.com",
    contactPhone: "010-1234-5678",
    contactCountry: "대한민국",
    isPrimary: "Y",
  })

  worksheet.addRow({
    vendorEmail: "example@company.com",
    contactName: "김철수",
    contactPosition: "과장",
    contactEmail: "kim@company.com",
    contactPhone: "010-9876-5432",
    contactCountry: "대한민국",
    isPrimary: "N",
  })

  const buffer = await workbook.xlsx.writeBuffer()
  return new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  })
}

/**
 * Excel 파일에서 연락처 데이터 파싱
 */
export async function parseContactImportFile(file: File): Promise<ImportContactData[]> {
  const arrayBuffer = await file.arrayBuffer()
  const workbook = new ExcelJS.Workbook()
  await workbook.xlsx.load(arrayBuffer)

  const worksheet = workbook.worksheets[0]
  if (!worksheet) {
    throw new Error("Excel 파일에 워크시트가 없습니다.")
  }

  const data: ImportContactData[] = []

  worksheet.eachRow((row, index) => {
    console.log(`행 ${index} 처리 중:`, row.values)
    // 헤더 행 건너뛰기 (1행)
    if (index === 1) return

    const values = row.values as (string | null)[]
    if (!values || values.length < 4) return

    const vendorEmail = values[1]?.toString().trim()
    const contactName = values[2]?.toString().trim()
    const contactPosition = values[3]?.toString().trim()
    const contactEmail = values[4]?.toString().trim()
    const contactPhone = values[5]?.toString().trim()
    const contactCountry = values[6]?.toString().trim()
    const isPrimary = values[7]?.toString().trim()

    // 필수 필드 검증
    if (!vendorEmail || !contactName || !contactEmail) {
      return
    }

    data.push({
      vendorEmail,
      contactName,
      contactPosition: contactPosition || undefined,
      contactEmail,
      contactPhone: contactPhone || undefined,
      contactCountry: contactCountry || undefined,
      isPrimary: isPrimary === "Y" || isPrimary === "y",
    })

    // rowNumber++
  })

  return data
}

// ================================================
// Possible Items Excel Import 관련 함수들
// ================================================

export interface PossibleItemImportData {
  vendorEmail: string
  itemCode: string
  itemType: "조선" | "해양TOP" | "해양HULL"
}

export interface PossibleItemImportResult {
  success: boolean
  totalRows: number
  successCount: number
  failedRows: Array<{
    row: number
    error: string
    vendorEmail: string
    itemCode: string
    itemType: "조선" | "해양TOP" | "해양HULL"
  }>
}

export interface PossibleItemErrorData {
  vendorEmail: string
  itemCode: string
  itemType: string
  error: string
}

export interface FoundItem {
  id: number
  itemCode: string | null
  workType: string | null
  itemList: string | null
  shipTypes: string | null
  itemType: "SHIP" | "TOP" | "HULL"
}

/**
 * 벤더 이메일로 벤더 찾기 (possible items import용)
 */
async function findVendorByEmail(email: string) {
  const vendor = await db
    .select({
      id: techVendors.id,
      vendorName: techVendors.vendorName,
      email: techVendors.email,
      techVendorType: techVendors.techVendorType,
    })
    .from(techVendors)
    .where(eq(techVendors.email, email))
    .limit(1)

  return vendor[0] || null
}

/**
 * 아이템 타입과 코드로 아이템 찾기
 * 조선의 경우 같은 아이템 코드에 선종이 다른 여러 레코드가 있을 수 있으므로 배열로 반환
 */
async function findItemByCodeAndType(itemCode: string, itemType: "조선" | "해양TOP" | "해양HULL"): Promise<FoundItem[]> {
  try {
    switch (itemType) {
      case "조선":
        const shipItems = await db
          .select({
            id: itemShipbuilding.id,
            itemCode: itemShipbuilding.itemCode,
            workType: itemShipbuilding.workType,
            itemList: itemShipbuilding.itemList,
            shipTypes: itemShipbuilding.shipTypes,
          })
          .from(itemShipbuilding)
          .where(eq(itemShipbuilding.itemCode, itemCode))

        return shipItems.length > 0
          ? shipItems.map(item => ({ ...item, itemType: "SHIP" as const }))
          : []

      case "해양TOP":
        const topItems = await db
          .select({
            id: itemOffshoreTop.id,
            itemCode: itemOffshoreTop.itemCode,
            workType: itemOffshoreTop.workType,
            itemList: itemOffshoreTop.itemList,
            shipTypes: sql<string>`null`.as("shipTypes"),
          })
          .from(itemOffshoreTop)
          .where(eq(itemOffshoreTop.itemCode, itemCode))

        return topItems.length > 0
          ? topItems.map(item => ({ ...item, itemType: "TOP" as const }))
          : []

      case "해양HULL":
        const hullItems = await db
          .select({
            id: itemOffshoreHull.id,
            itemCode: itemOffshoreHull.itemCode,
            workType: itemOffshoreHull.workType,
            itemList: itemOffshoreHull.itemList,
            shipTypes: sql<string>`null`.as("shipTypes"),
          })
          .from(itemOffshoreHull)
          .where(eq(itemOffshoreHull.itemCode, itemCode))

        return hullItems.length > 0
          ? hullItems.map(item => ({ ...item, itemType: "HULL" as const }))
          : []

      default:
        return []
    }
  } catch (error) {
    console.error("Error finding item:", error)
    return []
  }
}

/**
 * tech-vendor-possible-items에 중복 데이터 확인
 * 여러 아이템 ID를 한 번에 확인할 수 있도록 수정
 */
async function checkPossibleItemDuplicate(vendorId: number, items: FoundItem[]) {
  try {
    if (items.length === 0) return []

    const shipIds = items.filter(item => item.itemType === "SHIP").map(item => item.id)
    const topIds = items.filter(item => item.itemType === "TOP").map(item => item.id)
    const hullIds = items.filter(item => item.itemType === "HULL").map(item => item.id)

    const whereConditions = [eq(techVendorPossibleItems.vendorId, vendorId)]
    const orConditions = []

    if (shipIds.length > 0) {
      orConditions.push(inArray(techVendorPossibleItems.shipbuildingItemId, shipIds))
    }
    if (topIds.length > 0) {
      orConditions.push(inArray(techVendorPossibleItems.offshoreTopItemId, topIds))
    }
    if (hullIds.length > 0) {
      orConditions.push(inArray(techVendorPossibleItems.offshoreHullItemId, hullIds))
    }

    if (orConditions.length > 0) {
      whereConditions.push(or(...orConditions))
    }

    const existing = await db
      .select({
        id: techVendorPossibleItems.id,
        shipbuildingItemId: techVendorPossibleItems.shipbuildingItemId,
        offshoreTopItemId: techVendorPossibleItems.offshoreTopItemId,
        offshoreHullItemId: techVendorPossibleItems.offshoreHullItemId,
      })
      .from(techVendorPossibleItems)
      .where(and(...whereConditions))

    return existing
  } catch (error) {
    console.error("Error checking duplicate:", error)
    return []
  }
}

/**
 * possible items Excel 파일에서 데이터 파싱
 */
export async function parsePossibleItemsImportFile(file: File): Promise<PossibleItemImportData[]> {
  const arrayBuffer = await file.arrayBuffer()
  const workbook = new ExcelJS.Workbook()
  await workbook.xlsx.load(arrayBuffer)

  const worksheet = workbook.worksheets[0]
  if (!worksheet) {
    throw new Error("Excel 파일에 워크시트가 없습니다.")
  }

  const data: PossibleItemImportData[] = []

  worksheet.eachRow((row, index) => {
    // 헤더 행 건너뛰기 (1행)
    if (index === 1) return

    const values = row.values as (string | null)[]
    if (!values || values.length < 3) return

    const vendorEmail = values[1]?.toString().trim()
    const itemCode = values[2]?.toString().trim()
    const itemType = values[3]?.toString().trim()

    // 필수 필드 검증
    if (!vendorEmail || !itemCode || !itemType) {
      return
    }

    // 아이템 타입 검증 및 변환
    let validatedItemType: "조선" | "해양TOP" | "해양HULL" | null = null
    if (itemType === "조선") {
      validatedItemType = "조선"
    } else if (itemType === "해양TOP") {
      validatedItemType = "해양TOP"
    } else if (itemType === "해양HULL") {
      validatedItemType = "해양HULL"
    }

    if (!validatedItemType) {
      return
    }

    data.push({
      vendorEmail,
      itemCode,
      itemType: validatedItemType,
    })
  })

  return data
}

/**
 * possible items 일괄 import
 */
export async function importPossibleItemsFromExcel(
  data: PossibleItemImportData[]
): Promise<PossibleItemImportResult> {
  const result: PossibleItemImportResult = {
    success: true,
    totalRows: data.length,
    successCount: 0,
    failedRows: [],
  }

  for (let i = 0; i < data.length; i++) {
    const row = data[i]
    const rowNumber = i + 1

    try {
      // 1. 벤더 이메일로 벤더 찾기
      if (!row.vendorEmail || !row.vendorEmail.trim()) {
        result.failedRows.push({
          row: rowNumber,
          error: "벤더 이메일은 필수입니다.",
          vendorEmail: row.vendorEmail,
          itemCode: row.itemCode,
          itemType: row.itemType as "조선" | "해양TOP" | "해양HULL",
        })
        continue
      }

      let vendor = await findVendorByEmail(row.vendorEmail.trim())
      
      // 2. 벤더 테이블에서 찾을 수 없는 경우, 담당자 테이블에서 찾기
      if (!vendor) {
        console.log(`벤더 테이블에서 찾을 수 없음, 담당자 테이블에서 검색: ${row.vendorEmail}`)
        
        // 담당자 테이블에서 해당 이메일로 검색
        const contact = await db.query.techVendorContacts.findFirst({
          where: eq(techVendorContacts.contactEmail, row.vendorEmail.trim()),
          columns: { vendorId: true, contactEmail: true }
        })
        
        if (contact) {
          console.log(`담당자 테이블에서 찾음, 벤더 ID: ${contact.vendorId}`)
          
          // 해당 벤더 정보 가져오기
          vendor = await db.query.techVendors.findFirst({
            where: eq(techVendors.id, contact.vendorId),
            columns: { id: true, vendorName: true, email: true }
          })
          
          if (vendor) {
            console.log(`담당자를 통해 벤더 찾음: ${vendor.vendorName}`)
          }
        }
      }
      
      if (!vendor) {
        result.failedRows.push({
          row: rowNumber,
          error: `벤더 이메일 '${row.vendorEmail}'을(를) 찾을 수 없습니다. (벤더 테이블과 담당자 테이블 모두에서 검색 실패)`,
          vendorEmail: row.vendorEmail,
          itemCode: row.itemCode,
          itemType: row.itemType as "조선" | "해양TOP" | "해양HULL",
        })
        continue
      }

      // 2. 아이템 코드로 아이템 찾기
      if (!row.itemCode || !row.itemCode.trim()) {
        result.failedRows.push({
          row: rowNumber,
          error: "아이템 코드는 필수입니다.",
          vendorEmail: row.vendorEmail,
          itemCode: row.itemCode,
          itemType: row.itemType as "조선" | "해양TOP" | "해양HULL",
        })
        continue
      }

      const items = await findItemByCodeAndType(row.itemCode.trim(), row.itemType)
      if (!items || items.length === 0) {
        result.failedRows.push({
          row: rowNumber,
          error: `아이템 코드 '${row.itemCode}'을(를) '${row.itemType}' 타입에서 찾을 수 없습니다.`,
          vendorEmail: row.vendorEmail,
          itemCode: row.itemCode,
          itemType: row.itemType as "조선" | "해양TOP" | "해양HULL",
        })
        continue
      }

      // 3. 중복 데이터 확인 (모든 아이템에 대해)
      const existingItems = await checkPossibleItemDuplicate(vendor.id, items)

      // 중복되지 않은 아이템들만 필터링
      const nonDuplicateItems = items.filter(item => {
        const existingItem = existingItems.find(existing => {
          if (item.itemType === "SHIP") {
            return existing.shipbuildingItemId === item.id
          } else if (item.itemType === "TOP") {
            return existing.offshoreTopItemId === item.id
          } else if (item.itemType === "HULL") {
            return existing.offshoreHullItemId === item.id
          }
          return false
        })
        return !existingItem
      })

      if (nonDuplicateItems.length === 0) {
        result.failedRows.push({
          row: rowNumber,
          error: "모든 아이템이 이미 등록되어 있습니다.",
          vendorEmail: row.vendorEmail,
          itemCode: row.itemCode,
          itemType: row.itemType as "조선" | "해양TOP" | "해양HULL",
        })
        continue
      }

      // 4. tech-vendor-possible-items에 데이터 삽입 (중복되지 않은 아이템들만)
      for (const item of nonDuplicateItems) {
        const insertData: {
          vendorId: number
          shipbuildingItemId?: number
          offshoreTopItemId?: number
          offshoreHullItemId?: number
        } = {
          vendorId: vendor.id,
        }

        if (item.itemType === "SHIP") {
          insertData.shipbuildingItemId = item.id
        } else if (item.itemType === "TOP") {
          insertData.offshoreTopItemId = item.id
        } else if (item.itemType === "HULL") {
          insertData.offshoreHullItemId = item.id
        }

        await db.insert(techVendorPossibleItems).values(insertData)
        result.successCount++
      }

      // 부분 성공/실패 처리: 일부 아이템만 등록된 경우
      const duplicateCount = items.length - nonDuplicateItems.length
      if (duplicateCount > 0) {
        result.failedRows.push({
          row: rowNumber,
          error: `${duplicateCount}개 아이템이 중복되어 제외되었습니다.`,
          vendorEmail: row.vendorEmail,
          itemCode: row.itemCode,
          itemType: row.itemType as "조선" | "해양TOP" | "해양HULL",
        })
      }

    } catch (error) {
      result.failedRows.push({
        row: rowNumber,
        error: error instanceof Error ? error.message : "알 수 없는 오류",
        vendorEmail: row.vendorEmail,
        itemCode: row.itemCode,
        itemType: row.itemType,
      })
    }
  }

  // 캐시 무효화
  revalidateTag("tech-vendor-possible-items")

  return result
}

/**
 * possible items 템플릿 Excel 파일 생성
 */
export async function generatePossibleItemsImportTemplate(): Promise<Blob> {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet("벤더_Possible_Items_템플릿")

  // 헤더 설정
  worksheet.columns = [
    { header: "벤더이메일*", key: "vendorEmail", width: 25 },
    { header: "아이템코드*", key: "itemCode", width: 20 },
    { header: "아이템타입*", key: "itemType", width: 15 },
  ]

  // 헤더 스타일 설정
  const headerRow = worksheet.getRow(1)
  headerRow.font = { bold: true }
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFE0E0E0" },
  }

  // 예시 데이터 추가
  worksheet.addRow({
    vendorEmail: "vendor@example.com",
    itemCode: "ITEM001",
    itemType: "조선",
  })

  worksheet.addRow({
    vendorEmail: "vendor@example.com",
    itemCode: "TOP001",
    itemType: "해양TOP",
  })

  worksheet.addRow({
    vendorEmail: "vendor@example.com",
    itemCode: "HULL001",
    itemType: "해양HULL",
  })

  // 설명 시트 추가
  const infoSheet = workbook.addWorksheet("설명")
  infoSheet.getColumn(1).width = 50
  infoSheet.getColumn(2).width = 100

  infoSheet.addRow(["템플릿 사용 방법"])
  infoSheet.addRow(["1. 벤더이메일", "벤더의 이메일 주소 (필수)"])
  infoSheet.addRow(["2. 아이템코드", "아이템 코드 (필수)"])
  infoSheet.addRow(["3. 아이템타입", "조선, 해양TOP, 해양HULL 중 하나 (필수)"])
  infoSheet.addRow([])
  infoSheet.addRow(["중요 안내"])
  infoSheet.addRow(["• 조선 아이템의 경우", "같은 아이템 코드라도 선종이 다른 여러 레코드가 있을 수 있습니다."])
  infoSheet.addRow(["• 조선 아이템 등록 시", "아이템 코드 하나로 선종이 다른 모든 레코드가 자동으로 등록됩니다."])
  infoSheet.addRow(["• 해양TOP/HULL의 경우", "아이템 코드 하나에 하나의 레코드만 존재합니다."])
  infoSheet.addRow([])
  infoSheet.addRow(["주의사항"])
  infoSheet.addRow(["• 벤더이메일은 시스템에 등록된 이메일이어야 합니다."])
  infoSheet.addRow(["• 아이템코드는 해당 타입의 아이템 테이블에 존재해야 합니다."])
  infoSheet.addRow(["• 이미 등록된 아이템-벤더 조합은 중복 등록되지 않습니다."])
  infoSheet.addRow(["• 조선 아이템의 경우 일부 선종만 중복인 경우 나머지 선종은 등록됩니다."])

  const buffer = await workbook.xlsx.writeBuffer()
  return new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  })
}

/**
 * possible items 에러 Excel 파일 생성
 */
export async function generatePossibleItemsErrorExcel(errors: PossibleItemErrorData[]): Promise<Blob> {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet("Import_에러_내역")

  // 헤더 설정
  worksheet.columns = [
    { header: "벤더이메일", key: "vendorEmail", width: 25 },
    { header: "아이템코드", key: "itemCode", width: 20 },
    { header: "아이템타입", key: "itemType", width: 15 },
    { header: "에러내용", key: "error", width: 50 },
  ]

  // 헤더 스타일 설정
  const headerRow = worksheet.getRow(1)
  headerRow.font = { bold: true }
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFFFCCCC" },
  }

  // 에러 데이터 추가
  errors.forEach(error => {
    worksheet.addRow({
      vendorEmail: error.vendorEmail,
      itemCode: error.itemCode,
      itemType: error.itemType,
      error: error.error,
    })
  })

  const buffer = await workbook.xlsx.writeBuffer()
  return new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  })
}

/* -----------------------------------------------------
   Distinct Contact Import 관련 함수들
----------------------------------------------------- */

export interface DistinctContactImportData {
  vendorName: string
  email: string
}

export interface DistinctContactImportResult {
  success: boolean
  totalRows: number
  successCount: number
  failedRows: Array<{
    row: number
    error: string
    vendorName: string
    email: string
  }>
}

/**
 * Distinct Contact Import용 템플릿 생성 (벤더명, 이메일만)
 */
export async function generateDistinctContactImportTemplate(): Promise<Blob> {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet("벤더담당자_템플릿")

  // 헤더 설정
  worksheet.columns = [
    { header: "벤더이름*", key: "vendorName", width: 25 },
    { header: "이메일*", key: "email", width: 30 },
  ]

  // 헤더 스타일 설정
  const headerRow = worksheet.getRow(1)
  headerRow.font = { bold: true }
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFE0E0E0" },
  }

  // 예시 데이터 추가
  worksheet.addRow({
    vendorName: "ABB",
    email: "dong-rak.cho@kr.abb.com",
  })

  worksheet.addRow({
    vendorName: "ABB",
    email: "woo-jin.joo@kr.abb.com",
  })

  worksheet.addRow({
    vendorName: "삼성중공업",
    email: "contact@samsung.com",
  })

  // 설명 시트 추가
  const infoSheet = workbook.addWorksheet("설명")
  infoSheet.getColumn(1).width = 50
  infoSheet.getColumn(2).width = 100

  infoSheet.addRow(["Distinct Contact Import 사용 방법"])
  infoSheet.addRow(["1. 벤더이름", "벤더의 이름 (필수)"])
  infoSheet.addRow(["2. 이메일", "담당자 이메일 주소 (필수)"])
  infoSheet.addRow([])
  infoSheet.addRow(["기능 설명"])
  infoSheet.addRow(["• 벤더이름과 이메일을 입력하면 자동으로 벤더를 찾습니다"])
  infoSheet.addRow(["• 벤더 대표 이메일과 다른 이메일인 경우에만 담당자로 추가됩니다"])
  infoSheet.addRow(["• 벤더 대표 이메일과 같은 이메일인 경우는 건너뜁니다"])
  infoSheet.addRow(["• 이미 등록된 담당자 이메일은 중복 등록되지 않습니다"])
  infoSheet.addRow([])
  infoSheet.addRow(["예시"])
  infoSheet.addRow(["ABB 벤더의 대표 이메일이 dong-rak.cho@kr.abb.com 인 경우:"])
  infoSheet.addRow(["  - dong-rak.cho@kr.abb.com 입력 시: 건너뜀 (대표 이메일과 동일)"])
  infoSheet.addRow(["  - woo-jin.joo@kr.abb.com 입력 시: 담당자로 추가됨"])

  const buffer = await workbook.xlsx.writeBuffer()
  return new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  })
}

/**
 * Distinct Contact Import용 Excel 파일 파싱
 */
export async function parseDistinctContactImportFile(file: File): Promise<DistinctContactImportData[]> {
  const arrayBuffer = await file.arrayBuffer()
  const workbook = new ExcelJS.Workbook()
  await workbook.xlsx.load(arrayBuffer)

  const worksheet = workbook.worksheets[0]
  if (!worksheet) {
    throw new Error("Excel 파일에 워크시트가 없습니다.")
  }

  const data: DistinctContactImportData[] = []

  worksheet.eachRow((row, index) => {
    // 헤더 행 건너뛰기 (1행)
    if (index === 1) return

    const values = row.values as (string | null)[]
    if (!values || values.length < 2) return

    const vendorName = values[1]?.toString().trim()
    const email = values[2]?.toString().trim()

    // 필수 필드 검증
    if (!vendorName || !email) {
      return
    }

    data.push({
      vendorName,
      email,
    })
  })

  return data
}

/**
 * 벤더명으로 벤더 찾기 함수 (대소문자 구분 없이)
 */
async function findVendorByName(vendorName: string) {
  const vendor = await db
    .select({
      id: techVendors.id,
      vendorName: techVendors.vendorName,
      email: techVendors.email,
    })
    .from(techVendors)
    .where(ilike(techVendors.vendorName, `%${vendorName}%`))
    .limit(1)

  return vendor[0] || null
}

/**
 * 벤더의 기본 담당자(대표 이메일) 조회
 */
async function getVendorPrimaryContact(vendorId: number) {
  const contact = await db
    .select({
      contactName: techVendorContacts.contactName,
      contactEmail: techVendorContacts.contactEmail,
    })
    .from(techVendorContacts)
    .where(
      and(
        eq(techVendorContacts.vendorId, vendorId),
        eq(techVendorContacts.contactEmail, techVendors.email) // 기본 담당자 체크
      )
    )
    .innerJoin(techVendors, eq(techVendorContacts.vendorId, techVendors.id))
    .limit(1)

  return contact[0] || null
}

/**
 * Distinct Contact Import 메인 함수
 */
export async function importTechVendorDistinctContacts(
  data: DistinctContactImportData[]
): Promise<DistinctContactImportResult> {
  const result: DistinctContactImportResult = {
    success: true,
    totalRows: data.length,
    successCount: 0,
    failedRows: [],
  }

  for (let i = 0; i < data.length; i++) {
    const row = data[i]
    const rowNumber = i + 1

    try {
      // 1. 벤더명으로 벤더 찾기
      if (!row.vendorName || !row.vendorName.trim()) {
        result.failedRows.push({
          row: rowNumber,
          error: "벤더이름은 필수입니다.",
          vendorName: row.vendorName,
          email: row.email,
        })
        continue
      }

      const vendor = await findVendorByName(row.vendorName.trim())
      if (!vendor) {
        result.failedRows.push({
          row: rowNumber,
          error: `벤더이름 '${row.vendorName}'을(를) 찾을 수 없습니다.`,
          vendorName: row.vendorName,
          email: row.email,
        })
        continue
      }

      // 2. 이메일 검증
      if (!row.email || !row.email.trim()) {
        result.failedRows.push({
          row: rowNumber,
          error: "이메일은 필수입니다.",
          vendorName: row.vendorName,
          email: row.email,
        })
        continue
      }

      // 이메일 형식 검증 (기본적인 검증)
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(row.email.trim())) {
        result.failedRows.push({
          row: rowNumber,
          error: "올바른 이메일 형식이 아닙니다.",
          vendorName: row.vendorName,
          email: row.email,
        })
        continue
      }

      const email = row.email.trim()

      // 3. 벤더 대표 이메일과 비교
      if (email === vendor.email) {
        result.failedRows.push({
          row: rowNumber,
          error: "벤더 대표 이메일과 동일하여 건너뜁니다.",
          vendorName: row.vendorName,
          email: row.email,
        })
        continue
      }

      // 4. 기존 담당자 중복 체크
      const existingContact = await db
        .select()
        .from(techVendorContacts)
        .where(
          and(
            eq(techVendorContacts.vendorId, vendor.id),
            eq(techVendorContacts.contactEmail, email)
          )
        )
        .limit(1)

      if (existingContact.length > 0) {
        result.failedRows.push({
          row: rowNumber,
          error: "이미 등록된 담당자 이메일입니다.",
          vendorName: row.vendorName,
          email: row.email,
        })
        continue
      }

      // 5. 기본 담당자 확인 (대표 이메일이 기본 담당자로 등록되어 있는지)
      const primaryContact = await getVendorPrimaryContact(vendor.id)

      // 6. 담당자 추가
      await db.insert(techVendorContacts).values({
        vendorId: vendor.id,
        contactName: `${row.vendorName} 담당자`, // 벤더명 + 담당자
        contactPosition: null,
        contactEmail: email,
        contactPhone: null,
        contactCountry: null,
        isPrimary: false,
      })

      result.successCount++
    } catch (error) {
      result.failedRows.push({
        row: rowNumber,
        error: error instanceof Error ? error.message : "알 수 없는 오류",
        vendorName: row.vendorName,
        email: row.email,
      })
    }
  }

  // 캐시 무효화
  revalidateTag("tech-vendor-contacts")

  return result
}

/* -----------------------------------------------------
   Contact Possible Items Import 관련 함수들
----------------------------------------------------- */

export interface ContactPossibleItemImportData {
  contactEmail: string
  itemCodes: string[] // 쉼표로 분리된 아이템코드 배열
}

export interface ContactPossibleItemImportResult {
  success: boolean
  totalRows: number
  successCount: number
  failedRows: Array<{
    row: number
    error: string
    contactEmail: string
    itemCode: string
  }>
}

export interface ContactPossibleItemErrorData {
  contactEmail: string
  itemCode: string
  error: string
}

/**
 * Contact Possible Items Import용 템플릿 생성 (이메일, 아이템코드)
 */
export async function generateContactPossibleItemsImportTemplate(): Promise<Blob> {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet("담당자별_아이템매핑_템플릿")

  // 헤더 설정
  worksheet.columns = [
    { header: "담당자이메일*", key: "contactEmail", width: 30 },
    { header: "아이템코드*", key: "itemCode", width: 20 },
  ]

  // 헤더 스타일 설정
  const headerRow = worksheet.getRow(1)
  headerRow.font = { bold: true }
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFE0E0E0" },
  }

  // 예시 데이터 추가
  worksheet.addRow({
    contactEmail: "dong-rak.cho@kr.abb.com",
    itemCode: "ITEM001,ITEM002",
  })

  worksheet.addRow({
    contactEmail: "woo-jin.joo@kr.abb.com",
    itemCode: "TOP001,TOP002,TOP003",
  })

  worksheet.addRow({
    contactEmail: "contact@samsung.com",
    itemCode: "HULL001",
  })

  worksheet.addRow({
    contactEmail: "test@example.com",
    itemCode: "BF8101,BF6101,BF8401,BF8201",
  })

  // 설명 시트 추가
  const infoSheet = workbook.addWorksheet("설명")
  infoSheet.getColumn(1).width = 50
  infoSheet.getColumn(2).width = 100

  infoSheet.addRow(["Contact Possible Items Import 사용 방법"])
  infoSheet.addRow(["1. 담당자이메일", "등록된 담당자의 이메일 주소 (필수)"])
  infoSheet.addRow(["2. 아이템코드", "기술영업 아이템 코드 (필수)"])
  infoSheet.addRow([])
  infoSheet.addRow(["기능 설명"])
  infoSheet.addRow(["• 담당자 이메일로 등록된 담당자를 찾습니다"])
  infoSheet.addRow(["• 담당자가 속한 벤더의 타입을 확인합니다"])
  infoSheet.addRow(["• 벤더 타입별로 해당 아이템 테이블에서 아이템코드를 검색합니다"])
  infoSheet.addRow(["• 찾은 아이템들을 벤더의 possible items에 추가합니다"])
  infoSheet.addRow(["• 추가된 possible item과 담당자를 연결합니다"])
  infoSheet.addRow([])
  infoSheet.addRow(["예시"])
  infoSheet.addRow(["ABB 벤더의 담당자 dong-rak.cho@kr.abb.com이 ITEM001,ITEM002를 담당하는 경우:"])
  infoSheet.addRow(["  - 해당 담당자의 벤더 타입을 확인 (조선, 해양TOP 등)"])
  infoSheet.addRow(["  - 해당 타입의 아이템 테이블에서 ITEM001과 ITEM002를 각각 검색"])
  infoSheet.addRow(["  - 찾은 아이템들을 벤더의 possible items에 추가 (중복 제외)"])
  infoSheet.addRow(["  - 추가된 아이템들과 담당자를 연결"])
  infoSheet.addRow([])
  infoSheet.addRow(["다중 아이템코드 지원"])
  infoSheet.addRow(["• 아이템코드 필드에 쉼표(,)로 구분하여 여러 아이템코드를 입력할 수 있습니다"])
  infoSheet.addRow(["• 예: ITEM001,ITEM002,BF8101,BF6101"])
  infoSheet.addRow(["• 각 아이템코드는 개별적으로 처리되며, 실패한 코드만 에러로 기록됩니다"])

  const buffer = await workbook.xlsx.writeBuffer()
  return new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  })
}

/**
 * Contact Possible Items Import용 Excel 파일 파싱
 */
export async function parseContactPossibleItemsImportFile(file: File): Promise<ContactPossibleItemImportData[]> {
  const arrayBuffer = await file.arrayBuffer()
  const workbook = new ExcelJS.Workbook()
  await workbook.xlsx.load(arrayBuffer)

  const worksheet = workbook.worksheets[0]
  if (!worksheet) {
    throw new Error("Excel 파일에 워크시트가 없습니다.")
  }

  const data: ContactPossibleItemImportData[] = []

  worksheet.eachRow((row, index) => {
    // 헤더 행 건너뛰기 (1행)
    if (index === 1) return

    const values = row.values as (string | null)[]
    if (!values || values.length < 2) return

    const contactEmail = values[1]?.toString().trim()
    const itemCodeStr = values[2]?.toString().trim()

    // 필수 필드 검증
    if (!contactEmail || !itemCodeStr) {
      return
    }

    // 아이템코드를 쉼표로 분리하고 공백 제거
    const itemCodes = itemCodeStr.split(',').map(code => code.trim()).filter(code => code.length > 0)

    if (itemCodes.length === 0) {
      return
    }

    data.push({
      contactEmail,
      itemCodes,
    })
  })

  return data
}

/**
 * 이메일로 담당자 찾기 함수
 */
async function findContactByEmail(email: string) {
  const contact = await db
    .select({
      id: techVendorContacts.id,
      contactName: techVendorContacts.contactName,
      contactEmail: techVendorContacts.contactEmail,
      vendorId: techVendorContacts.vendorId,
    })
    .from(techVendorContacts)
    .where(eq(techVendorContacts.contactEmail, email))
    .limit(1)

  return contact[0] || null
}

/**
 * 벤더의 타입별 아이템 찾기 함수
 */
async function findItemsByVendorType(vendorId: number, itemCode: string) {
  // 벤더 정보 조회로 타입 확인
  const vendor = await db.query.techVendors.findFirst({
    where: eq(techVendors.id, vendorId),
    columns: {
      techVendorType: true
    }
  })

  if (!vendor) {
    throw new Error("벤더를 찾을 수 없습니다.")
  }

  const foundItems = []

  // 벤더 타입 파싱 - 콤마로 구분된 문자열을 배열로 변환
  let vendorTypes: string[] = []
  if (typeof vendor.techVendorType === 'string') {
    vendorTypes = vendor.techVendorType.split(',').map(type => type.trim()).filter(type => type.length > 0)
  } else {
    vendorTypes = [vendor.techVendorType]
  }

  // 각 벤더 타입별로 아이템 검색
  for (const vendorType of vendorTypes) {
    switch (vendorType) {
      case "조선":
        const shipItems = await db
          .select({
            id: itemShipbuilding.id,
            itemCode: itemShipbuilding.itemCode,
          })
          .from(itemShipbuilding)
          .where(eq(itemShipbuilding.itemCode, itemCode))

        foundItems.push(...shipItems.map(item => ({ ...item, itemType: "SHIP" })))
        break

      case "해양TOP":
        const topItems = await db
          .select({
            id: itemOffshoreTop.id,
            itemCode: itemOffshoreTop.itemCode,
          })
          .from(itemOffshoreTop)
          .where(eq(itemOffshoreTop.itemCode, itemCode))

        foundItems.push(...topItems.map(item => ({ ...item, itemType: "TOP" })))
        break

      case "해양HULL":
        const hullItems = await db
          .select({
            id: itemOffshoreHull.id,
            itemCode: itemOffshoreHull.itemCode,
          })
          .from(itemOffshoreHull)
          .where(eq(itemOffshoreHull.itemCode, itemCode))

        foundItems.push(...hullItems.map(item => ({ ...item, itemType: "HULL" })))
        break
    }
  }

  return foundItems
}

/**
 * 벤더의 possible items에 아이템 추가 함수 (중복 체크 포함)
 */
async function addVendorPossibleItems(vendorId: number, items: Array<{id: number, itemType: string}>) {
  const addedItems = []

  for (const item of items) {
    // 중복 체크
    let existingItem = null

    if (item.itemType === "SHIP") {
      existingItem = await db.query.techVendorPossibleItems.findFirst({
        where: and(
          eq(techVendorPossibleItems.vendorId, vendorId),
          eq(techVendorPossibleItems.shipbuildingItemId, item.id)
        )
      })
    } else if (item.itemType === "TOP") {
      existingItem = await db.query.techVendorPossibleItems.findFirst({
        where: and(
          eq(techVendorPossibleItems.vendorId, vendorId),
          eq(techVendorPossibleItems.offshoreTopItemId, item.id)
        )
      })
    } else if (item.itemType === "HULL") {
      existingItem = await db.query.techVendorPossibleItems.findFirst({
        where: and(
          eq(techVendorPossibleItems.vendorId, vendorId),
          eq(techVendorPossibleItems.offshoreHullItemId, item.id)
        )
      })
    }

    if (!existingItem) {
      // 새 아이템 추가
      const insertData: {
        vendorId: number
        shipbuildingItemId?: number
        offshoreTopItemId?: number
        offshoreHullItemId?: number
      } = {
        vendorId,
      }

      if (item.itemType === "SHIP") {
        insertData.shipbuildingItemId = item.id
      } else if (item.itemType === "TOP") {
        insertData.offshoreTopItemId = item.id
      } else if (item.itemType === "HULL") {
        insertData.offshoreHullItemId = item.id
      }

      const [newItem] = await db
        .insert(techVendorPossibleItems)
        .values(insertData)
        .returning()

      addedItems.push(newItem)
    }
  }

  return addedItems
}

/**
 * Contact Possible Items Import 메인 함수
 */
export async function importContactPossibleItemsFromExcel(
  data: ContactPossibleItemImportData[]
): Promise<ContactPossibleItemImportResult> {
  const result: ContactPossibleItemImportResult = {
    success: true,
    totalRows: data.length,
    successCount: 0,
    failedRows: [],
  }

  for (let i = 0; i < data.length; i++) {
    const row = data[i]
    const rowNumber = i + 1

    try {
      // 1. 담당자 이메일로 담당자 찾기
      if (!row.contactEmail || !row.contactEmail.trim()) {
        result.failedRows.push({
          row: rowNumber,
          error: "담당자 이메일은 필수입니다.",
          contactEmail: row.contactEmail,
          itemCode: row.itemCode,
        })
        continue
      }

      const contact = await findContactByEmail(row.contactEmail.trim())
      if (!contact) {
        result.failedRows.push({
          row: rowNumber,
          error: `담당자 이메일 '${row.contactEmail}'을(를) 찾을 수 없습니다.`,
          contactEmail: row.contactEmail,
          itemCode: row.itemCode,
        })
        continue
      }

      // 2. 아이템 코드 배열 검증
      if (!row.itemCodes || row.itemCodes.length === 0) {
        result.failedRows.push({
          row: rowNumber,
          error: "아이템 코드는 필수입니다.",
          contactEmail: row.contactEmail,
          itemCode: row.itemCodes.join(', '),
        })
        continue
      }

      // 3. 각 아이템코드에 대해 처리
      for (const itemCode of row.itemCodes) {
        try {
          // 벤더 타입별로 아이템 검색
          const foundItems = await findItemsByVendorType(contact.vendorId, itemCode)

          if (foundItems.length === 0) {
            result.failedRows.push({
              row: rowNumber,
              error: `아이템 코드 '${itemCode}'을(를) 벤더 타입에서 찾을 수 없습니다.`,
              contactEmail: row.contactEmail,
              itemCode: itemCode,
            })
            continue
          }

          // 4. 벤더의 possible items에 아이템 추가 (중복 체크 포함)
          const addedItems = await addVendorPossibleItems(contact.vendorId, foundItems)

          if (addedItems.length === 0) {
            result.failedRows.push({
              row: rowNumber,
              error: `아이템 코드 '${itemCode}'은(는) 이미 등록되어 있습니다.`,
              contactEmail: row.contactEmail,
              itemCode: itemCode,
            })
            continue
          }

          // 5. 추가된 아이템들을 담당자와 연결
          for (const addedItem of addedItems) {
            await db.insert(techSalesContactPossibleItems).values({
              contactId: contact.id,
              vendorPossibleItemId: addedItem.id,
            })
          }

          result.successCount += addedItems.length
        } catch (error) {
          result.failedRows.push({
            row: rowNumber,
            error: `아이템 코드 '${itemCode}' 처리 중 오류: ${error instanceof Error ? error.message : '알 수 없는 오류'}`,
            contactEmail: row.contactEmail,
            itemCode: itemCode,
          })
        }
      }
      console.log(result)
    } catch (error) {
      result.failedRows.push({
        row: rowNumber,
        error: error instanceof Error ? error.message : "알 수 없는 오류",
        contactEmail: row.contactEmail,
        itemCode: row.itemCodes.join(', '),
      })
    }
  }

  // 캐시 무효화
  revalidateTag("tech-vendor-possible-items")
  revalidateTag("tech-sales-contact-possible-items")

  return result
}

/**
 * Contact Possible Items Import용 에러 엑셀 파일 생성
 */
export async function generateContactPossibleItemsErrorExcel(errors: Array<{
  contactEmail: string
  itemCode: string
  error: string
}>): Promise<Blob> {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet("Import_에러_내역")

  // 헤더 설정
  worksheet.columns = [
    { header: "담당자이메일", key: "contactEmail", width: 30 },
    { header: "아이템코드", key: "itemCode", width: 20 },
    { header: "에러내용", key: "error", width: 80, style: { alignment: { wrapText: true } } },
  ]

  // 헤더 스타일 설정
  const headerRow = worksheet.getRow(1)
  headerRow.font = { bold: true }
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFFFCCCC" },
  }

  // 에러 데이터 추가
  errors.forEach(error => {
    worksheet.addRow({
      contactEmail: error.contactEmail,
      itemCode: error.itemCode,
      error: error.error,
    })
  })

  const buffer = await workbook.xlsx.writeBuffer()
  return new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  })
}