summaryrefslogtreecommitdiff
path: root/lib/techsales-rfq/service.ts
blob: e35437525bc5f544f424cc749bdb5e617b176d13 (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
'use server'

import { unstable_noStore, revalidateTag, revalidatePath } from "next/cache";
import db from "@/db/db";
import { 
  techSalesRfqs, 
  techSalesVendorQuotations,
  techSalesVendorQuotationRevisions,
  techSalesAttachments,
  techSalesVendorQuotationAttachments,
  techSalesVendorQuotationContacts,
  techSalesContactPossibleItems,
  users,
  techSalesRfqComments,
  techSalesRfqItems,
  biddingProjects
} from "@/db/schema";
import { and, desc, eq, ilike, or, sql, inArray, count, asc, lt, ne } from "drizzle-orm";
import { unstable_cache } from "@/lib/unstable-cache";
import { filterColumns } from "@/lib/filter-columns";
import { getErrorMessage } from "@/lib/handle-error";
import type { Filter } from "@/types/table";
import { 
  selectTechSalesRfqsWithJoin,
  countTechSalesRfqsWithJoin,
  selectTechSalesVendorQuotationsWithJoin,
  countTechSalesVendorQuotationsWithJoin,
  selectTechSalesDashboardWithJoin,
  selectSingleTechSalesVendorQuotationWithJoin
} from "./repository";
import { GetTechSalesRfqsSchema } from "./validations";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { sendEmail } from "../mail/sendEmail";
import { formatDate } from "../utils";
import { itemShipbuilding, itemOffshoreTop, itemOffshoreHull } from "@/db/schema/items";
import { techVendors, techVendorPossibleItems, techVendorContacts } from "@/db/schema/techVendors";
import { deleteFile, saveDRMFile, saveFile } from "@/lib/file-stroage";
import { decryptWithServerAction } from "@/components/drm/drmUtils";

// 정렬 타입 정의
// 의도적으로 any 사용 - drizzle ORM의 orderBy 타입이 복잡함
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type OrderByType = any;

export type Project = {
  id: number;
  projectCode: string;
  projectName: string;
  pjtType: "SHIP" | "TOP" | "HULL";
}

/**
 * 연도별 순차 RFQ 코드 생성 함수 (다중 생성 지원)
 * 형식: RFQ-YYYY-001, RFQ-YYYY-002, ...
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function generateRfqCodes(tx: any, count: number, year?: number): Promise<string[]> {
  const currentYear = year || new Date().getFullYear();
  const yearPrefix = `RFQ-${currentYear}-`;
  
  // 해당 연도의 가장 최근 RFQ 코드 조회
  const latestRfq = await tx
    .select({ rfqCode: techSalesRfqs.rfqCode })
    .from(techSalesRfqs)
    .where(ilike(techSalesRfqs.rfqCode, `${yearPrefix}%`))
    .orderBy(desc(techSalesRfqs.rfqCode))
    .limit(1);

  let nextNumber = 1;
  
  if (latestRfq.length > 0) {
    // 기존 코드에서 번호 추출 (RFQ-2024-001 -> 001)
    const lastCode = latestRfq[0].rfqCode;
    const numberPart = lastCode.split('-').pop();
    if (numberPart) {
      const lastNumber = parseInt(numberPart, 10);
      if (!isNaN(lastNumber)) {
        nextNumber = lastNumber + 1;
      }
    }
  }
  
  // 요청된 개수만큼 순차적으로 코드 생성
  const codes: string[] = [];
  for (let i = 0; i < count; i++) {
    const paddedNumber = (nextNumber + i).toString().padStart(3, '0');
    codes.push(`${yearPrefix}${paddedNumber}`);
  }
  
  return codes;
}


/**
 * 직접 조인을 사용하여 RFQ 데이터 조회하는 함수
 * 페이지네이션, 필터링, 정렬 등 지원
 */
export async function getTechSalesRfqsWithJoin(input: GetTechSalesRfqsSchema & { rfqType?: "SHIP" | "TOP" | "HULL" }) {
  return unstable_cache(
    async () => {
      try {
        // 마감일이 지났고 아직 Closed가 아닌 RFQ를 일괄 Closed로 변경
        await db.update(techSalesRfqs)
          .set({ status: "Closed", updatedAt: new Date() })
          .where(
            and(
              lt(techSalesRfqs.dueDate, new Date()),
              ne(techSalesRfqs.status, "Closed")
            )
          );
        const offset = (input.page - 1) * input.perPage;

        // 기본 필터 처리 - RFQFilterBox에서 오는 필터
        const basicFilters = input.basicFilters || [];
        const basicJoinOperator = input.basicJoinOperator || "and";

        // 고급 필터 처리 - workTypes을 먼저 제외
        const advancedFilters = (input.filters || []).filter(f => f.id !== "workTypes");
        const advancedJoinOperator = input.joinOperator || "and";

        // workTypes 필터는 별도로 추출
        const workTypesFilter = (input.filters || []).find(f => f.id === "workTypes");

        // 기본 필터 조건 생성
        let basicWhere;
        if (basicFilters.length > 0) {
          basicWhere = filterColumns({
            table: techSalesRfqs,
            filters: basicFilters,
            joinOperator: basicJoinOperator,
          });
        }

        // 고급 필터 조건 생성 (workTypes 제외)
        let advancedWhere;
        if (advancedFilters.length > 0) {
          advancedWhere = filterColumns({
            table: techSalesRfqs,
            filters: advancedFilters,
            joinOperator: advancedJoinOperator,
          });
        }

        // 전역 검색 조건
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(techSalesRfqs.rfqCode, s),
            ilike(techSalesRfqs.materialCode, s),
            ilike(techSalesRfqs.description, s),
            ilike(techSalesRfqs.remark, s)
          );
        }

        // workTypes 필터 처리 (고급 필터에서 제외된 workTypes만 별도 처리)
        let workTypesWhere;
        if (workTypesFilter && Array.isArray(workTypesFilter.value) && workTypesFilter.value.length > 0) {
          // RFQ 아이템 테이블들과 조인하여 workType이 포함된 RFQ만 추출
          // (조선, 해양TOP, 해양HULL 모두 포함)
          const rfqIdsWithWorkTypes = db
            .selectDistinct({ rfqId: techSalesRfqItems.rfqId })
            .from(techSalesRfqItems)
            .leftJoin(itemShipbuilding, eq(techSalesRfqItems.itemShipbuildingId, itemShipbuilding.id))
            .leftJoin(itemOffshoreTop, eq(techSalesRfqItems.itemOffshoreTopId, itemOffshoreTop.id))
            .leftJoin(itemOffshoreHull, eq(techSalesRfqItems.itemOffshoreHullId, itemOffshoreHull.id))
            .where(
              or(
                inArray(itemShipbuilding.workType, workTypesFilter.value),
                inArray(itemOffshoreTop.workType, workTypesFilter.value),
                inArray(itemOffshoreHull.workType, workTypesFilter.value)
              )
            );
          workTypesWhere = inArray(techSalesRfqs.id, rfqIdsWithWorkTypes);
        }

        // 모든 조건 결합
        const whereConditions = [];
        if (basicWhere) whereConditions.push(basicWhere);
        if (advancedWhere) whereConditions.push(advancedWhere);
        if (globalWhere) whereConditions.push(globalWhere);
        if (workTypesWhere) whereConditions.push(workTypesWhere);

        // 조건이 있을 때만 and() 사용
        const finalWhere = whereConditions.length > 0
          ? and(...whereConditions)
          : undefined;

        // 정렬 기준 설정
        let orderBy: OrderByType[] = [desc(techSalesRfqs.createdAt)]; // 기본 정렬
        
        if (input.sort?.length) {
          // 안전하게 접근하여 정렬 기준 설정
          orderBy = input.sort.map(item => {
            // TypeScript 에러 방지를 위한 타입 단언
            const sortField = item.id as string;
            
            switch (sortField) {
              case 'id':
                return item.desc ? desc(techSalesRfqs.id) : techSalesRfqs.id;
              case 'rfqCode':
                return item.desc ? desc(techSalesRfqs.rfqCode) : techSalesRfqs.rfqCode;
              case 'materialCode':
                return item.desc ? desc(techSalesRfqs.materialCode) : techSalesRfqs.materialCode;
              case 'description':
                return item.desc ? desc(techSalesRfqs.description) : techSalesRfqs.description;
              case 'status':
                return item.desc ? desc(techSalesRfqs.status) : techSalesRfqs.status;
              case 'dueDate':
                return item.desc ? desc(techSalesRfqs.dueDate) : techSalesRfqs.dueDate;
              case 'rfqSendDate':
                return item.desc ? desc(techSalesRfqs.rfqSendDate) : techSalesRfqs.rfqSendDate;
              case 'remark':
                return item.desc ? desc(techSalesRfqs.remark) : techSalesRfqs.remark;
              case 'createdAt':
                return item.desc ? desc(techSalesRfqs.createdAt) : techSalesRfqs.createdAt;
              case 'updatedAt':
                return item.desc ? desc(techSalesRfqs.updatedAt) : techSalesRfqs.updatedAt;
              default:
                return item.desc ? desc(techSalesRfqs.createdAt) : techSalesRfqs.createdAt;
            }
          });
        }

        // Repository 함수 호출 - rfqType 매개변수 추가
        return await db.transaction(async (tx) => {
          const [data, total] = await Promise.all([
            selectTechSalesRfqsWithJoin(tx, {
              where: finalWhere,
              orderBy,
              offset,
              limit: input.perPage,
              rfqType: input.rfqType,
            }),
            countTechSalesRfqsWithJoin(tx, finalWhere, input.rfqType),
          ]);

          const pageCount = Math.ceil(Number(total) / input.perPage);
          return { data, pageCount, total: Number(total) };
        });
      } catch (err) {
        console.error("Error fetching RFQs with join:", err);
        return { data: [], pageCount: 0, total: 0 };
      }
    },
    [JSON.stringify(input)],
    {
      revalidate: 60,
      tags: ["techSalesRfqs"],
    }
  )();
}

/**
 * 직접 조인을 사용하여 벤더 견적서 조회하는 함수
 */
export async function getTechSalesVendorQuotationsWithJoin(input: {
  rfqId?: number;
  vendorId?: number;
  search?: string;
  filters?: Filter<typeof techSalesVendorQuotations>[];
  sort?: { id: string; desc: boolean }[];
  page: number;
  perPage: number;
  rfqType?: "SHIP" | "TOP" | "HULL"; // rfqType 매개변수 추가
}) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // 기본 필터 조건들
        const whereConditions = [];

        // RFQ ID 필터
        if (input.rfqId) {
          whereConditions.push(eq(techSalesVendorQuotations.rfqId, input.rfqId));
        }

        // 벤더 ID 필터
        if (input.vendorId) {
          whereConditions.push(eq(techSalesVendorQuotations.vendorId, input.vendorId));
        }

        // 검색 조건
        if (input.search) {
          const s = `%${input.search}%`;
          const searchCondition = or(
              ilike(techSalesVendorQuotations.currency, s),
              ilike(techSalesVendorQuotations.status, s)
          );
          if (searchCondition) {
            whereConditions.push(searchCondition);
          }
        }

        // 고급 필터 처리
        if (input.filters && input.filters.length > 0) {
          const filterWhere = filterColumns({
            table: techSalesVendorQuotations,
            filters: input.filters as Filter<typeof techSalesVendorQuotations>[],
            joinOperator: "and",
          });
          if (filterWhere) {
            whereConditions.push(filterWhere);
          }
        }

        // 최종 WHERE 조건
        const finalWhere = whereConditions.length > 0 
          ? and(...whereConditions) 
          : undefined;

        // 정렬 기준 설정
        let orderBy: OrderByType[] = [desc(techSalesVendorQuotations.createdAt)];
        
        if (input.sort?.length) {
          orderBy = input.sort.map(item => {
            switch (item.id) {
              case 'id':
                return item.desc ? desc(techSalesVendorQuotations.id) : techSalesVendorQuotations.id;
              case 'status':
                return item.desc ? desc(techSalesVendorQuotations.status) : techSalesVendorQuotations.status;
              case 'currency':
                return item.desc ? desc(techSalesVendorQuotations.currency) : techSalesVendorQuotations.currency;
              case 'totalPrice':
                return item.desc ? desc(techSalesVendorQuotations.totalPrice) : techSalesVendorQuotations.totalPrice;
              case 'createdAt':
                return item.desc ? desc(techSalesVendorQuotations.createdAt) : techSalesVendorQuotations.createdAt;
              case 'updatedAt':
                return item.desc ? desc(techSalesVendorQuotations.updatedAt) : techSalesVendorQuotations.updatedAt;
              default:
                return item.desc ? desc(techSalesVendorQuotations.createdAt) : techSalesVendorQuotations.createdAt;
            }
          });
        }

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

          // 각 견적서의 첨부파일 정보 조회
          const dataWithAttachments = await Promise.all(
            data.map(async (quotation) => {
              const attachments = await db.query.techSalesVendorQuotationAttachments.findMany({
                where: eq(techSalesVendorQuotationAttachments.quotationId, quotation.id),
                orderBy: [desc(techSalesVendorQuotationAttachments.createdAt)],
              });

              return {
                ...quotation,
                quotationAttachments: attachments.map(att => ({
                  id: att.id,
                  fileName: att.fileName,
                  fileSize: att.fileSize,
                  filePath: att.filePath,
                  description: att.description,
                }))
              };
            })
          );

          const total = await countTechSalesVendorQuotationsWithJoin(tx, finalWhere);
          return { data: dataWithAttachments, total };
        });

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

        return { data, pageCount, total };
      } catch (err) {
        console.error("Error fetching vendor quotations with join:", err);
        return { data: [], pageCount: 0, total: 0 };
      }
    },
    [JSON.stringify(input)],
    {
      revalidate: 60,
      tags: [
        "techSalesVendorQuotations",
        ...(input.rfqId ? [`techSalesRfq-${input.rfqId}`] : [])
      ],
    }
  )();
}

/**
 * 직접 조인을 사용하여 RFQ 대시보드 데이터 조회하는 함수
 */
export async function getTechSalesDashboardWithJoin(input: {
    search?: string;
  filters?: Filter<typeof techSalesRfqs>[];
  sort?: { id: string; desc: boolean }[];
  page: number;
  perPage: number;
  rfqType?: "SHIP" | "TOP" | "HULL"; // rfqType 매개변수 추가
}) {
  unstable_noStore(); // 대시보드는 항상 최신 데이터를 보여주기 위해 캐시하지 않음

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

    // Advanced filtering
    const advancedWhere = input.filters ? filterColumns({
      table: techSalesRfqs,
      filters: input.filters as Filter<typeof techSalesRfqs>[],
      joinOperator: 'and',
    }) : undefined;

    // Global search
    let globalWhere;
    if (input.search) {
      const s = `%${input.search}%`;
      globalWhere = or(
        ilike(techSalesRfqs.rfqCode, s),
        ilike(techSalesRfqs.materialCode, s),
        ilike(techSalesRfqs.description, s)
      );
    }

    const finalWhere = and(
      advancedWhere,
      globalWhere
    );

    // 정렬 기준 설정
    let orderBy: OrderByType[] = [desc(techSalesRfqs.updatedAt)]; // 기본 정렬
    
    if (input.sort?.length) {
      // 안전하게 접근하여 정렬 기준 설정
      orderBy = input.sort.map(item => {
        switch (item.id) {
          case 'id':
            return item.desc ? desc(techSalesRfqs.id) : techSalesRfqs.id;
          case 'rfqCode':
            return item.desc ? desc(techSalesRfqs.rfqCode) : techSalesRfqs.rfqCode;
          case 'status':
            return item.desc ? desc(techSalesRfqs.status) : techSalesRfqs.status;
          case 'dueDate':
            return item.desc ? desc(techSalesRfqs.dueDate) : techSalesRfqs.dueDate;
          case 'createdAt':
            return item.desc ? desc(techSalesRfqs.createdAt) : techSalesRfqs.createdAt;
          case 'updatedAt':
            return item.desc ? desc(techSalesRfqs.updatedAt) : techSalesRfqs.updatedAt;
          default:
            return item.desc ? desc(techSalesRfqs.updatedAt) : techSalesRfqs.updatedAt;
        }
      });
    }

    // 트랜잭션 내부에서 Repository 호출
    const data = await db.transaction(async (tx) => {
      return await selectTechSalesDashboardWithJoin(tx, {
        where: finalWhere,
        orderBy,
        offset,
        limit: input.perPage,
        rfqType: input.rfqType, // rfqType 매개변수 추가
      });
    });

    return { data, success: true };
  } catch (err) {
    console.error("Error fetching dashboard data with join:", err);
    return { data: [], success: false, error: getErrorMessage(err) };
  }
}

/**
 * 특정 RFQ의 벤더 목록 조회
 */
export async function getTechSalesRfqVendors(rfqId: number) {
  unstable_noStore();
  try {
    // Repository 함수를 사용하여 벤더 견적 목록 조회
    const result = await getTechSalesVendorQuotationsWithJoin({
      rfqId,
      page: 1,
      perPage: 1000, // 충분히 큰 수로 설정하여 모든 벤더 조회
    });

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

/**
 * 기술영업 RFQ 발송 (선택된 벤더들의 선택된 contact들에게)
 */
export async function sendTechSalesRfqToVendors(input: {
  rfqId: number;
  vendorIds: number[];
  selectedContacts?: Array<{
    vendorId: number;
    contactId: number;
    contactEmail: string;
    contactName: string;
  }>;
}) {
  unstable_noStore();
  try {
    // 인증 확인
    const session = await getServerSession(authOptions);

    if (!session?.user) {
      return {
        success: false,
        message: "인증이 필요합니다",
      };
    }

    // RFQ 정보 조회
    const rfq = await db.query.techSalesRfqs.findFirst({
      where: eq(techSalesRfqs.id, input.rfqId),
      columns: {
        id: true,
        rfqCode: true,
        status: true,
        dueDate: true,
        rfqSendDate: true,
        remark: true,
        materialCode: true,
        description: true,
        rfqType: true,
      },
      with: {
        biddingProject: true,
        createdByUser: {
          columns: {
            id: true,
            name: true,
            email: true,
          }
        }
      }
    });

    if (!rfq) {
      return {
        success: false,
        message: "RFQ를 찾을 수 없습니다",
      };
    }

    // 발송 가능한 상태인지 확인
    if (rfq.status !== "RFQ Vendor Assignned" && rfq.status !== "RFQ Sent") {
      return {
        success: false,
        message: "벤더가 할당된 RFQ 또는 이미 전송된 RFQ만 다시 전송할 수 있습니다",
      };
    }

    const isResend = rfq.status === "RFQ Sent";

    // 현재 사용자 정보 조회
    const sender = await db.query.users.findFirst({
      where: eq(users.id, Number(session.user.id)),
      columns: {
        id: true,
        email: true,
        name: true,
      }
    });

    if (!sender || !sender.email) {
      return {
        success: false,
        message: "보내는 사람의 이메일 정보를 찾을 수 없습니다",
      };
    }

    // 선택된 벤더들의 견적서 정보 조회
    const vendorQuotations = await db.query.techSalesVendorQuotations.findMany({
      where: and(
        eq(techSalesVendorQuotations.rfqId, input.rfqId),
        inArray(techSalesVendorQuotations.vendorId, input.vendorIds)
      ),
      columns: {
        id: true,
        vendorId: true,
        status: true,
        currency: true,
      },
      with: {
        vendor: {
          columns: {
            id: true,
            vendorName: true,
            vendorCode: true,
          }
        }
      }
    });

    if (vendorQuotations.length === 0) {
      return {
        success: false,
        message: "선택된 벤더가 이 RFQ에 할당되어 있지 않습니다",
      };
    }

    // 트랜잭션 시작
    await db.transaction(async (tx) => {
      // 1. RFQ 상태 업데이트 (최초 발송인 경우 rfqSendDate 설정)
      const updateData: Partial<typeof techSalesRfqs.$inferInsert> = {
        status: "RFQ Sent",
        sentBy: Number(session.user.id),
        updatedBy: Number(session.user.id),
        updatedAt: new Date(),
      };

      // rfqSendDate가 null인 경우에만 최초 전송일 설정
      if (!rfq.rfqSendDate) {
        updateData.rfqSendDate = new Date();
      }

      await tx.update(techSalesRfqs)
        .set(updateData)
        .where(eq(techSalesRfqs.id, input.rfqId));

      // 2. 선택된 벤더들의 견적서 상태를 "Assigned"에서 "Draft"로 변경
      for (const quotation of vendorQuotations) {
        if (quotation.status === "Assigned") {
          await tx.update(techSalesVendorQuotations)
            .set({
              status: "Draft",
              updatedBy: Number(session.user.id),
              updatedAt: new Date(),
            })
            .where(eq(techSalesVendorQuotations.id, quotation.id));
        }
      }

      // 3. 각 벤더에 대해 이메일 발송 처리
      for (const quotation of vendorQuotations) {
        if (!quotation.vendorId || !quotation.vendor) continue;

        let vendorEmailsString = "";

        // contact 기반 발송 또는 기존 방식 (모든 벤더 사용자)
        if (input.selectedContacts && input.selectedContacts.length > 0) {
          // 선택된 contact들에게만 발송
          const vendorContacts = input.selectedContacts.filter(
            contact => contact.vendorId === quotation.vendor!.id
          );
          
          if (vendorContacts.length > 0) {
            vendorEmailsString = vendorContacts
              .map(contact => contact.contactEmail)
              .join(", ");
          }
        } else {
          // 기존 방식: 벤더에 속한 모든 사용자에게 발송
          const vendorUsers = await db.query.users.findMany({
            where: eq(users.companyId, quotation.vendor.id),
            columns: {
              id: true,
              email: true,
              name: true,
              language: true
            }
          });

          vendorEmailsString = vendorUsers
            .filter(user => user.email)
            .map(user => user.email)
            .join(", ");
        }

        if (vendorEmailsString) {
          // 대표 언어 결정 (기본값 한국어)
          const language = "ko";

          // RFQ 아이템 목록 조회
          const rfqItemsResult = await getTechSalesRfqItems(rfq.id);
          const rfqItems = rfqItemsResult.data || [];

          // 이메일 컨텍스트 구성
          const emailContext = {
            language: language,
            rfq: {
              id: rfq.id,
              code: rfq.rfqCode,
              title: rfqItems.length > 0 ? rfqItems.map(item => item.itemList).join(', ') : '',
              projectCode: rfq.biddingProject?.pspid || '',
              projectName: rfq.biddingProject?.projNm || '',
              description: rfq.remark || '',
              dueDate: rfq.dueDate ? formatDate(rfq.dueDate, "KR") : 'N/A',
              materialCode: rfq.materialCode || '',
              type: rfq.rfqType || 'SHIP',
            },
            items: rfqItems.map(item => ({
              itemCode: item.itemCode,
              itemList: item.itemList,
              workType: item.workType,
              shipTypes: item.shipTypes,
              subItemList: item.subItemList,
              itemType: item.itemType,
            })),
            vendor: {
              id: quotation.vendor.id,
              code: quotation.vendor.vendorCode || '',
              name: quotation.vendor.vendorName,
            },
            sender: {
              fullName: sender.name || '',
              email: sender.email,
            },
            project: {
              id: rfq.biddingProject?.pspid || '',
              name: rfq.biddingProject?.projNm || '',
              sector: rfq.biddingProject?.sector || '',
              shipType: rfq.biddingProject?.ptypeNm || '',
              shipCount: rfq.biddingProject?.projMsrm || 0,
              ownerName: rfq.biddingProject?.kunnrNm || '',
              className: rfq.biddingProject?.cls1Nm || '',
            },
            details: {
              currency: quotation.currency || 'USD',
            },
            quotationCode: `${rfq.rfqCode}-${quotation.vendorId}`,
            systemUrl: process.env.NEXT_PUBLIC_APP_URL || 'http://60.101.108.100/ko/partners',
            isResend: isResend,
            versionInfo: isResend ? '(재전송)' : '',
          }



          // 이메일 전송
          await sendEmail({
            to: vendorEmailsString,
            subject: isResend 
              ? `[기술영업 RFQ 재전송] ${rfq.rfqCode} - ${rfqItems.length > 0 ? rfqItems.map(item => item.itemList).join(', ') : '견적 요청'} ${emailContext.versionInfo}`
              : `[기술영업 RFQ] ${rfq.rfqCode} - ${rfqItems.length > 0 ? rfqItems.map(item => item.itemList).join(', ') : '견적 요청'}`,
            template: 'tech-sales-rfq-invite-ko', // 기술영업용 템플릿
            context: emailContext,
            cc: sender.email, // 발신자를 CC에 추가
          });

          // 4. 선택된 담당자 정보를 quotation_contacts 테이블에 저장
          if (input.selectedContacts && input.selectedContacts.length > 0) {
            const vendorContacts = input.selectedContacts.filter(
              contact => contact.vendorId === quotation.vendor!.id
            );

            for (const contact of vendorContacts) {
              // quotation_contacts 중복 체크
              const existingQuotationContact = await tx.query.techSalesVendorQuotationContacts.findFirst({
                where: and(
                  eq(techSalesVendorQuotationContacts.quotationId, quotation.id),
                  eq(techSalesVendorQuotationContacts.contactId, contact.contactId)
                )
              });

              if (!existingQuotationContact) {
                await tx.insert(techSalesVendorQuotationContacts).values({
                  quotationId: quotation.id,
                  contactId: contact.contactId,
                  createdAt: new Date(),
                  updatedAt: new Date(),
                });
              }

              // 5. 담당자별 아이템 매핑 정보 저장 (중복 방지)
              for (const item of rfqItems) {
                let vendorPossibleItem = null;
                // 조선: 아이템코드 + 선종으로 조선아이템테이블에서 찾기, 해양: 아이템코드로만 찾기
                if (item.itemType === "SHIP" && item.itemCode && item.shipTypes) {
                  // 조선: itemShipbuilding에서 itemCode, shipTypes로 찾기
                  const shipbuildingItem = await tx.query.itemShipbuilding.findFirst({
                    where: and(
                      eq(itemShipbuilding.itemCode, item.itemCode),
                      eq(itemShipbuilding.shipTypes, item.shipTypes)
                    )
                  });
                  if (shipbuildingItem?.id) {
                    vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
                      where: and(
                        eq(techVendorPossibleItems.vendorId, quotation.vendor!.id),
                        eq(techVendorPossibleItems.shipbuildingItemId, shipbuildingItem.id)
                      )
                    });
                  }
                } else if (item.itemType === "TOP" && item.itemCode) {
                  // 해양 TOP: itemOffshoreTop에서 itemCode로 찾기
                  const offshoreTopItem = await tx.query.itemOffshoreTop.findFirst({
                    where: eq(itemOffshoreTop.itemCode, item.itemCode)
                  });
                  if (offshoreTopItem?.id) {
                    vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
                      where: and(
                        eq(techVendorPossibleItems.vendorId, quotation.vendor!.id),
                        eq(techVendorPossibleItems.offshoreTopItemId, offshoreTopItem.id)
                      )
                    });
                  }
                } else if (item.itemType === "HULL" && item.itemCode) {
                  // 해양 HULL: itemOffshoreHull에서 itemCode로 찾기
                  const offshoreHullItem = await tx.query.itemOffshoreHull.findFirst({
                    where: eq(itemOffshoreHull.itemCode, item.itemCode)
                  });
                  if (offshoreHullItem?.id) {
                    vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
                      where: and(
                        eq(techVendorPossibleItems.vendorId, quotation.vendor!.id),
                        eq(techVendorPossibleItems.offshoreHullItemId, offshoreHullItem.id)
                      )
                    });
                  }
                }

                if (vendorPossibleItem) {
                  // contact_possible_items 중복 체크
                  const existingContactPossibleItem = await tx.query.techSalesContactPossibleItems.findFirst({
                    where: and(
                      eq(techSalesContactPossibleItems.contactId, contact.contactId),
                      eq(techSalesContactPossibleItems.vendorPossibleItemId, vendorPossibleItem.id)
                    )
                  });

                  if (!existingContactPossibleItem) {
                    await tx.insert(techSalesContactPossibleItems).values({
                      contactId: contact.contactId,
                      vendorPossibleItemId: vendorPossibleItem.id,
                      createdAt: new Date(),
                      updatedAt: new Date(),
                    });
                  }
                }
              }
            }
          }
        }
      }
    });

    // 캐시 무효화
    revalidateTag("techSalesRfqs");
    revalidateTag("techSalesVendorQuotations");
    revalidateTag(`techSalesRfq-${input.rfqId}`);
    revalidatePath(getTechSalesRevalidationPath(rfq?.rfqType || "SHIP"));

    const sentContactCount = input.selectedContacts?.length || vendorQuotations.length;
    const messageDetail = input.selectedContacts && input.selectedContacts.length > 0 
      ? `${sentContactCount}명의 연락처에게 RFQ가 성공적으로 발송되었습니다`
      : `${vendorQuotations.length}개 벤더에게 RFQ가 성공적으로 발송되었습니다`;

    return {
      success: true,
      message: messageDetail,
      sentCount: sentContactCount,
    };
  } catch (err) {
    console.error("기술영업 RFQ 발송 오류:", err);
    return {
      success: false,
      message: "RFQ 발송 중 오류가 발생했습니다",
    };
  }
}

/**
 * 벤더용 기술영업 RFQ 견적서 조회 (withJoin 사용)
 */
export async function getTechSalesVendorQuotation(quotationId: number) {
  unstable_noStore();
  try {
    const quotation = await db.transaction(async (tx) => {
      return await selectSingleTechSalesVendorQuotationWithJoin(tx, quotationId);
    });

    if (!quotation) {
      return { data: null, error: "견적서를 찾을 수 없습니다." };
    }

    // RFQ 아이템 정보도 함께 조회
    const itemsResult = await getTechSalesRfqItems(quotation.rfqId);
    const items = itemsResult.data || [];

    // 견적서 첨부파일 조회
    const quotationAttachments = await db.query.techSalesVendorQuotationAttachments.findMany({
      where: eq(techSalesVendorQuotationAttachments.quotationId, quotationId),
      orderBy: [desc(techSalesVendorQuotationAttachments.createdAt)],
    });

    // 기존 구조와 호환되도록 데이터 재구성
    const formattedQuotation = {
      id: quotation.id,
      rfqId: quotation.rfqId,
      vendorId: quotation.vendorId,
      quotationCode: quotation.quotationCode,
      quotationVersion: quotation.quotationVersion,
      totalPrice: quotation.totalPrice,
      currency: quotation.currency,
      validUntil: quotation.validUntil,
      status: quotation.status,
      remark: quotation.remark,
      rejectionReason: quotation.rejectionReason,
      submittedAt: quotation.submittedAt,
      acceptedAt: quotation.acceptedAt,
      createdAt: quotation.createdAt,
      updatedAt: quotation.updatedAt,
      createdBy: quotation.createdBy,
      updatedBy: quotation.updatedBy,
      
      // RFQ 정보
      rfq: {
        id: quotation.rfqId,
        rfqCode: quotation.rfqCode,
        rfqType: quotation.rfqType,
        status: quotation.rfqStatus,
        dueDate: quotation.dueDate,
        rfqSendDate: quotation.rfqSendDate,
        materialCode: quotation.materialCode,
        description: quotation.description,
        remark: quotation.rfqRemark,
        picCode: quotation.picCode,
        createdBy: quotation.rfqCreatedBy,
        biddingProjectId: quotation.biddingProjectId,
        
        // 아이템 정보 추가
        items: items,
        
        // 생성자 정보
        createdByUser: {
          id: quotation.rfqCreatedBy,
          name: quotation.rfqCreatedByName,
          email: quotation.rfqCreatedByEmail,
        },
        
        // 프로젝트 정보
        biddingProject: quotation.biddingProjectId ? {
          id: quotation.biddingProjectId,
          pspid: quotation.pspid,
          projNm: quotation.projNm,
          sector: quotation.sector,
          projMsrm: quotation.projMsrm,
          ptypeNm: quotation.ptypeNm,
        } : null,
      },
      
      // 벤더 정보
      vendor: {
        id: quotation.vendorId,
        vendorName: quotation.vendorName,
        vendorCode: quotation.vendorCode,
        country: quotation.vendorCountry,
        email: quotation.vendorEmail,
        phone: quotation.vendorPhone,
      },

      // 첨부파일 정보
      quotationAttachments: quotationAttachments.map(attachment => ({
        id: attachment.id,
        fileName: attachment.fileName,
        fileSize: attachment.fileSize,
        filePath: attachment.filePath,
        description: attachment.description,
      }))
    };

    return { data: formattedQuotation, error: null };
  } catch (err) {
    console.error("Error fetching vendor quotation:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 벤더 견적서 업데이트 (임시저장),
 * 현재는 submit으로 처리, revision 을 아래의 함수로 사용가능함.
 */
export async function updateTechSalesVendorQuotation(data: {
  id: number
  currency: string
  totalPrice: string
  validUntil: Date
  remark?: string
  updatedBy: number
  changeReason?: string
}) {
  try {
    return await db.transaction(async (tx) => {
      // 현재 견적서 전체 데이터 조회 (revision 저장용)
      const currentQuotation = await tx.query.techSalesVendorQuotations.findFirst({
        where: eq(techSalesVendorQuotations.id, data.id),
      });

      if (!currentQuotation) {
        return { data: null, error: "견적서를 찾을 수 없습니다." };
      }

      // Accepted나 Rejected 상태가 아니면 수정 가능
      if (["Rejected"].includes(currentQuotation.status)) {
        return { data: null, error: "승인되거나 거절된 견적서는 수정할 수 없습니다." };
      }

      // 실제 변경사항이 있는지 확인
      const hasChanges = 
        currentQuotation.currency !== data.currency ||
        currentQuotation.totalPrice !== data.totalPrice ||
        currentQuotation.validUntil?.getTime() !== data.validUntil.getTime() ||
        currentQuotation.remark !== (data.remark || null);

      if (!hasChanges) {
        return { data: currentQuotation, error: null };
      }

      // 현재 버전을 revision history에 저장
      await tx.insert(techSalesVendorQuotationRevisions).values({
        quotationId: data.id,
        version: currentQuotation.quotationVersion || 1,
        snapshot: {
          currency: currentQuotation.currency,
          totalPrice: currentQuotation.totalPrice,
          validUntil: currentQuotation.validUntil,
          remark: currentQuotation.remark,
          status: currentQuotation.status,
          quotationVersion: currentQuotation.quotationVersion,
          submittedAt: currentQuotation.submittedAt,
          acceptedAt: currentQuotation.acceptedAt,
          updatedAt: currentQuotation.updatedAt,
        },
        changeReason: data.changeReason || "견적서 수정",
        revisedBy: data.updatedBy,
      });

      // 새로운 버전으로 업데이트
      const result = await tx
        .update(techSalesVendorQuotations)
        .set({
          currency: data.currency,
          totalPrice: data.totalPrice,
          validUntil: data.validUntil,
          remark: data.remark || null,
          quotationVersion: (currentQuotation.quotationVersion || 1) + 1,
          status: "Revised", // 수정된 상태로 변경
          updatedAt: new Date(),
        })
        .where(eq(techSalesVendorQuotations.id, data.id))
        .returning();

      return { data: result[0], error: null };
    });
  } catch (error) {
    console.error("Error updating tech sales vendor quotation:", error);
    return { data: null, error: "견적서 업데이트 중 오류가 발생했습니다" };
  } finally {
    // 캐시 무효화
    revalidateTag("techSalesVendorQuotations");
    revalidatePath(`/partners/techsales/rfq-ship/${data.id}`);
  }
}

/**
 * 기술영업 벤더 견적서 제출
 */
export async function submitTechSalesVendorQuotation(data: {
  id: number
  currency: string
  totalPrice: string
  validUntil: Date
  remark?: string
  attachments?: Array<{
    fileName: string
    originalFileName: string
    filePath: string
    fileSize: number
  }>
  updatedBy: number
}) {
  try {
    return await db.transaction(async (tx) => {
      // 현재 견적서 전체 데이터 조회 (revision 저장용)
      const currentQuotation = await tx.query.techSalesVendorQuotations.findFirst({
        where: eq(techSalesVendorQuotations.id, data.id),
      });

      if (!currentQuotation) {
        return { data: null, error: "견적서를 찾을 수 없습니다." };
      }

      // Rejected 상태에서는 제출 불가
      if (["Rejected"].includes(currentQuotation.status)) {
        return { data: null, error: "거절된 견적서는 제출할 수 없습니다." };
      }
      
      // // 실제 변경사항이 있는지 확인
      // const hasChanges = 
      //   currentQuotation.currency !== data.currency ||
      //   currentQuotation.totalPrice !== data.totalPrice ||
      //   currentQuotation.validUntil?.getTime() !== data.validUntil.getTime() ||
      //   currentQuotation.remark !== (data.remark || null);

      // // 변경사항이 있거나 처음 제출하는 경우 revision 저장
      // if (hasChanges || currentQuotation.status === "Draft") {
      //   await tx.insert(techSalesVendorQuotationRevisions).values({
      //     quotationId: data.id,
      //     version: currentQuotation.quotationVersion || 1,
      //     snapshot: {
      //       currency: currentQuotation.currency,
      //       totalPrice: currentQuotation.totalPrice,
      //       validUntil: currentQuotation.validUntil,
      //       remark: currentQuotation.remark,
      //       status: currentQuotation.status,
      //       quotationVersion: currentQuotation.quotationVersion,
      //       submittedAt: currentQuotation.submittedAt,
      //       acceptedAt: currentQuotation.acceptedAt,
      //       updatedAt: currentQuotation.updatedAt,
      //     },
      //     changeReason: "견적서 제출",
      //     revisedBy: data.updatedBy,
      //   });
      // }

      // 첫 제출인지 확인 (quotationVersion이 null인 경우)
      const isFirstSubmission = currentQuotation.quotationVersion === null;
      
      // 첫 제출이 아닌 경우에만 revision 저장 (변경사항 이력 관리)
      if (!isFirstSubmission) {
        await tx.insert(techSalesVendorQuotationRevisions).values({
          quotationId: data.id,
          version: currentQuotation.quotationVersion || 1,
          snapshot: {
            currency: currentQuotation.currency,
            totalPrice: currentQuotation.totalPrice,
            validUntil: currentQuotation.validUntil,
            remark: currentQuotation.remark,
            status: currentQuotation.status,
            quotationVersion: currentQuotation.quotationVersion,
            submittedAt: currentQuotation.submittedAt,
            acceptedAt: currentQuotation.acceptedAt,
            updatedAt: currentQuotation.updatedAt,
          },
          changeReason: "견적서 제출",
          revisedBy: data.updatedBy,
        });
      }

      // 새로운 버전 번호 계산 (첫 제출은 1, 재제출은 1 증가)
      const newRevisionId = isFirstSubmission ? 1 : (currentQuotation.quotationVersion || 1) + 1;

      // 새로운 버전으로 업데이트
      const result = await tx
        .update(techSalesVendorQuotations)
        .set({
          currency: data.currency,
          totalPrice: data.totalPrice,
          validUntil: data.validUntil,
          remark: data.remark || null,
          quotationVersion: newRevisionId,
          status: "Submitted",
          submittedAt: new Date(),
          updatedAt: new Date(),
        })
        .where(eq(techSalesVendorQuotations.id, data.id))
        .returning();

      // 첨부파일 처리 (새로운 revisionId 사용)
      if (data.attachments && data.attachments.length > 0) {
        for (const attachment of data.attachments) {
          await tx.insert(techSalesVendorQuotationAttachments).values({
            quotationId: data.id,
            revisionId: newRevisionId, // 새로운 리비전 ID 사용
            fileName: attachment.fileName, // 해시된 파일명 (저장용)
            originalFileName: attachment.originalFileName, // 원본 파일명 (표시용)
            fileSize: attachment.fileSize,
            filePath: attachment.filePath,
            fileType: attachment.originalFileName.split('.').pop() || 'unknown',
            uploadedBy: data.updatedBy,
            isVendorUpload: true,
          });
        }
      }

      // 메일 발송 (백그라운드에서 실행)
      if (result[0]) {
        // 벤더에게 견적 제출 확인 메일 발송
        sendQuotationSubmittedNotificationToVendor(data.id).catch(error => {
          console.error("벤더 견적 제출 확인 메일 발송 실패:", error);
        });

        // 담당자에게 견적 접수 알림 메일 발송
        sendQuotationSubmittedNotificationToManager(data.id).catch(error => {
          console.error("담당자 견적 접수 알림 메일 발송 실패:", error);
        });
      }

      return { data: result[0], error: null };
    });
  } catch (error) {
    console.error("Error submitting tech sales vendor quotation:", error);
    return { data: null, error: "견적서 제출 중 오류가 발생했습니다" };
  } finally {
    // 캐시 무효화
    revalidateTag("techSalesVendorQuotations");
    revalidatePath(`/partners/techsales/rfq-ship`);
  }
}

/**
 * 통화 목록 조회
 */
export async function fetchCurrencies() {
  try {
    // 기본 통화 목록 (실제로는 DB에서 가져와야 함)
    const currencies = [
      { code: "USD", name: "미국 달러" },
      { code: "KRW", name: "한국 원" },
      { code: "EUR", name: "유로" },
      { code: "JPY", name: "일본 엔" },
      { code: "CNY", name: "중국 위안" },
    ]

    return { data: currencies, error: null }
  } catch (error) {
    console.error("Error fetching currencies:", error)
    return { data: null, error: "통화 목록 조회 중 오류가 발생했습니다" }
  }
}

/**
 * 벤더용 기술영업 견적서 목록 조회 (페이지네이션 포함)
 */
export async function getVendorQuotations(input: {
  flags?: string[];
  page: number;
  perPage: number;
  sort?: { id: string; desc: boolean }[];
  filters?: Filter<typeof techSalesVendorQuotations>[];
  joinOperator?: "and" | "or";
  basicFilters?: Filter<typeof techSalesVendorQuotations>[];
  basicJoinOperator?: "and" | "or";
  search?: string;
  from?: string;
  to?: string;
  rfqType?: "SHIP" | "TOP" | "HULL";
}, vendorId: string) {
  return unstable_cache(
    async () => {
      try {


        const { page, perPage, sort, filters = [], search = "", from = "", to = "" } = input;
        const offset = (page - 1) * perPage;
        const limit = perPage;

        // 기본 조건: 해당 벤더의 견적서만 조회 (Assigned 상태 제외)
        const vendorIdNum = parseInt(vendorId);
        if (isNaN(vendorIdNum)) {
          console.error('❌ [getVendorQuotations] Invalid vendorId:', vendorId);
          return { data: [], pageCount: 0, total: 0 };
        }

        const baseConditions = [
          eq(techSalesVendorQuotations.vendorId, vendorIdNum),
          sql`${techSalesVendorQuotations.status} != 'Assigned'` // Assigned 상태 제외
        ];

        // rfqType 필터링 추가
        if (input.rfqType) {
          baseConditions.push(eq(techSalesRfqs.rfqType, input.rfqType));
        }

        // 검색 조건 추가
        if (search) {
          const s = `%${search}%`;
          const searchCondition = or(
            ilike(techSalesVendorQuotations.currency, s),
            ilike(techSalesVendorQuotations.status, s)
          );
          if (searchCondition) {
            baseConditions.push(searchCondition);
          }
        }

        // 날짜 범위 필터
        if (from) {
          baseConditions.push(sql`${techSalesVendorQuotations.createdAt} >= ${from}`);
        }
        if (to) {
          baseConditions.push(sql`${techSalesVendorQuotations.createdAt} <= ${to}`);
        }

        // 고급 필터 처리
        if (filters.length > 0) {
          const filterWhere = filterColumns({
            table: techSalesVendorQuotations,
            filters: filters as Filter<typeof techSalesVendorQuotations>[],
            joinOperator: input.joinOperator || "and",
          });
          if (filterWhere) {
            baseConditions.push(filterWhere);
          }
        }

        // 최종 WHERE 조건
        const finalWhere = baseConditions.length > 0 
          ? and(...baseConditions) 
          : undefined;

        // 정렬 기준 설정
        let orderBy: OrderByType[] = [desc(techSalesVendorQuotations.updatedAt)];
        
        if (sort?.length) {
          orderBy = sort.map(item => {
            switch (item.id) {
              case 'id':
                return item.desc ? desc(techSalesVendorQuotations.id) : techSalesVendorQuotations.id;
              case 'status':
                return item.desc ? desc(techSalesVendorQuotations.status) : techSalesVendorQuotations.status;
              case 'currency':
                return item.desc ? desc(techSalesVendorQuotations.currency) : techSalesVendorQuotations.currency;
              case 'totalPrice':
                return item.desc ? desc(techSalesVendorQuotations.totalPrice) : techSalesVendorQuotations.totalPrice;
              case 'validUntil':
                return item.desc ? desc(techSalesVendorQuotations.validUntil) : techSalesVendorQuotations.validUntil;
              case 'submittedAt':
                return item.desc ? desc(techSalesVendorQuotations.submittedAt) : techSalesVendorQuotations.submittedAt;
              case 'createdAt':
                return item.desc ? desc(techSalesVendorQuotations.createdAt) : techSalesVendorQuotations.createdAt;
              case 'updatedAt':
                return item.desc ? desc(techSalesVendorQuotations.updatedAt) : techSalesVendorQuotations.updatedAt;
              case 'rfqCode':
                return item.desc ? desc(techSalesRfqs.rfqCode) : techSalesRfqs.rfqCode;
              case 'materialCode':
                return item.desc ? desc(techSalesRfqs.materialCode) : techSalesRfqs.materialCode;
              case 'dueDate':
                return item.desc ? desc(techSalesRfqs.dueDate) : techSalesRfqs.dueDate;
              case 'rfqStatus':
                return item.desc ? desc(techSalesRfqs.status) : techSalesRfqs.status;
              default:
                return item.desc ? desc(techSalesVendorQuotations.updatedAt) : techSalesVendorQuotations.updatedAt;
            }
          });
        }

        // 조인을 포함한 데이터 조회 (중복 제거를 위해 techSalesAttachments JOIN 제거)
        const data = await db
          .select({
            id: techSalesVendorQuotations.id,
            rfqId: techSalesVendorQuotations.rfqId,
            vendorId: techSalesVendorQuotations.vendorId,
            status: techSalesVendorQuotations.status,
            currency: techSalesVendorQuotations.currency,
            totalPrice: techSalesVendorQuotations.totalPrice,
            validUntil: techSalesVendorQuotations.validUntil,
            submittedAt: techSalesVendorQuotations.submittedAt,
            remark: techSalesVendorQuotations.remark,
            createdAt: techSalesVendorQuotations.createdAt,
            updatedAt: techSalesVendorQuotations.updatedAt,
            createdBy: techSalesVendorQuotations.createdBy,
            updatedBy: techSalesVendorQuotations.updatedBy,
            quotationCode: techSalesVendorQuotations.quotationCode,
            quotationVersion: techSalesVendorQuotations.quotationVersion,
            rejectionReason: techSalesVendorQuotations.rejectionReason,
            acceptedAt: techSalesVendorQuotations.acceptedAt,
            // RFQ 정보
            rfqCode: techSalesRfqs.rfqCode,
            materialCode: techSalesRfqs.materialCode,
            dueDate: techSalesRfqs.dueDate,
            rfqStatus: techSalesRfqs.status,
            description: techSalesRfqs.description,
            // 프로젝트 정보 (직접 조인)
            projNm: biddingProjects.projNm,
            // 아이템 개수
            itemCount: sql<number>`(
              SELECT COUNT(*) 
              FROM tech_sales_rfq_items 
              WHERE tech_sales_rfq_items.rfq_id = ${techSalesRfqs.id}
            )`,
            // RFQ 첨부파일 개수 (RFQ_COMMON 타입만 카운트)
            attachmentCount: sql<number>`(
              SELECT COUNT(*) 
              FROM tech_sales_attachments 
              WHERE tech_sales_attachments.tech_sales_rfq_id = ${techSalesRfqs.id}
              AND tech_sales_attachments.attachment_type = 'RFQ_COMMON'
            )`,
          })
          .from(techSalesVendorQuotations)
          .leftJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id))
          .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id))
          .where(finalWhere)
          .orderBy(...orderBy)
          .limit(limit)
          .offset(offset);

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

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

        return { data, pageCount, total };
      } catch (err) {
        console.error("Error fetching vendor quotations:", err);
        return { data: [], pageCount: 0, total: 0 };
      }
    },
    [JSON.stringify(input), vendorId], // 캐싱 키
    {
      revalidate: 60, // 1분간 캐시
      tags: [
        "techSalesVendorQuotations", 
        `vendor-${vendorId}-quotations`
      ],
    }
  )();
}

/**
 * 기술영업 벤더 견적 승인 (벤더 선택)
 */
export async function acceptTechSalesVendorQuotation(quotationId: number) {
  try {
    const result = await db.transaction(async (tx) => {
      // 1. 선택된 견적 정보 조회
      const selectedQuotation = await tx
        .select()
        .from(techSalesVendorQuotations)
        .where(eq(techSalesVendorQuotations.id, quotationId))
        .limit(1)

      if (selectedQuotation.length === 0) {
        throw new Error("견적을 찾을 수 없습니다")
      }

      const quotation = selectedQuotation[0]

      // 2. 선택된 견적을 Accepted로 변경
      await tx
        .update(techSalesVendorQuotations)
        .set({
          status: "Accepted",
          acceptedAt: new Date(),
          updatedAt: new Date(),
        })
        .where(eq(techSalesVendorQuotations.id, quotationId))

      // 4. RFQ 상태를 Closed로 변경
      await tx
        .update(techSalesRfqs)
        .set({
          status: "Closed",
          updatedAt: new Date(),
        })
        .where(eq(techSalesRfqs.id, quotation.rfqId))

      return quotation
    })

    // // 메일 발송 (백그라운드에서 실행)
    // // 선택된 벤더에게 견적 선택 알림 메일 발송
    // sendQuotationAcceptedNotification(quotationId).catch(error => {
    //   console.error("벤더 견적 선택 알림 메일 발송 실패:", error);
    // });

    // 캐시 무효화
    revalidateTag("techSalesVendorQuotations")
    revalidateTag(`techSalesRfq-${result.rfqId}`)
    revalidateTag("techSalesRfqs")

    // 해당 RFQ의 모든 벤더 캐시 무효화 (선택된 벤더와 거절된 벤더들)
    const allVendorsInRfq = await db.query.techSalesVendorQuotations.findMany({
      where: eq(techSalesVendorQuotations.rfqId, result.rfqId),
      columns: { vendorId: true }
    });
    
    for (const vendorQuotation of allVendorsInRfq) {
      revalidateTag(`vendor-${vendorQuotation.vendorId}-quotations`);
    }
    revalidatePath("/evcp/budgetary-tech-sales-ship")
    revalidatePath("/partners/techsales")
    

    return { success: true, data: result }
  } catch (error) {
    console.error("벤더 견적 승인 오류:", error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "벤더 견적 승인에 실패했습니다" 
    }
  }
}

/**
 * 기술영업 RFQ 첨부파일 생성
 */
export async function createTechSalesRfqAttachments(params: {
  techSalesRfqId: number
  files: File[]
  createdBy: number
  attachmentType?: "RFQ_COMMON" | "VENDOR_SPECIFIC"
  description?: string
}) {
  unstable_noStore();
  try {
    const { techSalesRfqId, files, createdBy, attachmentType = "RFQ_COMMON", description } = params;
    

    
    if (!files || files.length === 0) {
      return { data: null, error: "업로드할 파일이 없습니다." };
    }

    // RFQ 존재 확인
    const rfq = await db.query.techSalesRfqs.findFirst({
      where: eq(techSalesRfqs.id, techSalesRfqId),
      columns: { id: true, status: true }
    });

    if (!rfq) {
      return { data: null, error: "RFQ를 찾을 수 없습니다." };
    }

    // // 편집 가능한 상태 확인
    // if (!["RFQ Created", "RFQ Vendor Assignned"].includes(rfq.status)) {
    //   return { data: null, error: "현재 상태에서는 첨부파일을 추가할 수 없습니다." };
    // }

    const results: typeof techSalesAttachments.$inferSelect[] = [];

    // 트랜잭션으로 처리
    await db.transaction(async (tx) => {

      for (const file of files) {

        
        const saveResult = await saveDRMFile(
          file,
          decryptWithServerAction,
          `techsales-rfq/${techSalesRfqId}`
        );

        if (!saveResult.success) {
          throw new Error(saveResult.error || "파일 저장에 실패했습니다.");
        }

        // DB에 첨부파일 레코드 생성
        const [newAttachment] = await tx.insert(techSalesAttachments).values({
          techSalesRfqId,
          attachmentType,
          fileName: saveResult.fileName!,
          originalFileName: file.name,
          filePath: saveResult.publicPath!,
          fileSize: file.size,
          fileType: file.type || undefined,
          description: description || undefined,
          createdBy,
        }).returning();

        results.push(newAttachment);
      }
    });



    // RFQ 타입 조회하여 캐시 무효화
    const rfqType = await db.query.techSalesRfqs.findFirst({
      where: eq(techSalesRfqs.id, techSalesRfqId),
      columns: { rfqType: true }
    });
    
    revalidateTag("techSalesRfqs");
    revalidateTag(`techSalesRfq-${techSalesRfqId}`);
    revalidatePath(getTechSalesRevalidationPath(rfqType?.rfqType || "SHIP"));
    revalidatePath("/partners/techsales");
    return { data: results, error: null };
  } catch (err) {
    console.error("기술영업 RFQ 첨부파일 생성 오류:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 RFQ 첨부파일 조회
 */
export async function getTechSalesRfqAttachments(techSalesRfqId: number) {
  unstable_noStore();
  try {
    const attachments = await db.query.techSalesAttachments.findMany({
      where: eq(techSalesAttachments.techSalesRfqId, techSalesRfqId),
      orderBy: [desc(techSalesAttachments.createdAt)],
      with: {
        createdByUser: {
          columns: {
            id: true,
            name: true,
            email: true,
          }
        }
      }
    });

    return { data: attachments, error: null };
  } catch (err) {
    console.error("기술영업 RFQ 첨부파일 조회 오류:", err);
    return { data: [], error: getErrorMessage(err) };
  }
}

/**
 * RFQ 첨부파일 타입별 조회
 */
export async function getTechSalesRfqAttachmentsByType(
  techSalesRfqId: number, 
  attachmentType: "RFQ_COMMON" | "VENDOR_SPECIFIC" | "TBE_RESULT" | "CBE_RESULT"
) {
  unstable_noStore();
  try {
    const attachments = await db.query.techSalesAttachments.findMany({
      where: and(
        eq(techSalesAttachments.techSalesRfqId, techSalesRfqId),
        eq(techSalesAttachments.attachmentType, attachmentType)
      ),
      orderBy: [desc(techSalesAttachments.createdAt)],
      with: {
        createdByUser: {
          columns: {
            id: true,
            name: true,
            email: true,
          }
        }
      }
    });

    return { data: attachments, error: null };
  } catch (err) {
    console.error(`기술영업 RFQ ${attachmentType} 첨부파일 조회 오류:`, err);
    return { data: [], error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 RFQ 첨부파일 삭제
 */
export async function deleteTechSalesRfqAttachment(attachmentId: number) {
  unstable_noStore();
  try {
    // 첨부파일 정보 조회
    const attachment = await db.query.techSalesAttachments.findFirst({
      where: eq(techSalesAttachments.id, attachmentId),
    });

    if (!attachment) {
      return { data: null, error: "첨부파일을 찾을 수 없습니다." };
    }

    // RFQ 상태 확인
    const rfq = await db.query.techSalesRfqs.findFirst({
      where: eq(techSalesRfqs.id, attachment.techSalesRfqId!), // Non-null assertion since we know it exists
      columns: { id: true, status: true }
    });

    if (!rfq) {
      return { data: null, error: "RFQ를 찾을 수 없습니다." };
    }

    // // 편집 가능한 상태 확인
    // if (!["RFQ Created", "RFQ Vendor Assignned"].includes(rfq.status)) {
    //   return { data: null, error: "현재 상태에서는 첨부파일을 삭제할 수 없습니다." };
    // }

    // 트랜잭션으로 처리
    const result = await db.transaction(async (tx) => {
      // DB에서 레코드 삭제
      const deletedAttachment = await tx.delete(techSalesAttachments)
        .where(eq(techSalesAttachments.id, attachmentId))
        .returning();

      // 파일 시스템에서 파일 삭제
      try {
        deleteFile(attachment.filePath)

      } catch (fileError) {
        console.warn("파일 삭제 실패:", fileError);
        // 파일 삭제 실패는 심각한 오류가 아니므로 계속 진행
      }

      return deletedAttachment[0];
    });

    // RFQ 타입 조회하여 캐시 무효화
    const attachmentRfq = await db.query.techSalesRfqs.findFirst({
      where: eq(techSalesRfqs.id, attachment.techSalesRfqId!),
      columns: { rfqType: true }
    });
    
    revalidateTag("techSalesRfqs");
    revalidateTag(`techSalesRfq-${attachment.techSalesRfqId}`);
    revalidatePath(getTechSalesRevalidationPath(attachmentRfq?.rfqType || "SHIP"));

    return { data: result, error: null };
  } catch (err) {
    console.error("기술영업 RFQ 첨부파일 삭제 오류:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 RFQ 첨부파일 일괄 처리 (업로드 + 삭제)
 */
export async function processTechSalesRfqAttachments(params: {
  techSalesRfqId: number
  newFiles: { file: File; attachmentType: "RFQ_COMMON" | "VENDOR_SPECIFIC" | "TBE_RESULT" | "CBE_RESULT"; description?: string }[]
  deleteAttachmentIds: number[]
  createdBy: number
}) {
  unstable_noStore();
  try {
    const { techSalesRfqId, newFiles, deleteAttachmentIds, createdBy } = params;



    // RFQ 존재 및 상태 확인
    const rfq = await db.query.techSalesRfqs.findFirst({
      where: eq(techSalesRfqs.id, techSalesRfqId),
      columns: { id: true, status: true }
    });

    if (!rfq) {
      return { data: null, error: "RFQ를 찾을 수 없습니다." };
    }
    // // 편집 가능한 상태 확인
    // if (!["RFQ Created", "RFQ Vendor Assignned"].includes(rfq.status)) {
    //   return { data: null, error: "현재 상태에서는 첨부파일을 수정할 수 없습니다." };
    // }

    const results = {
      uploaded: [] as typeof techSalesAttachments.$inferSelect[],
      deleted: [] as typeof techSalesAttachments.$inferSelect[],
    };

    await db.transaction(async (tx) => {

      // 1. 삭제할 첨부파일 처리
      if (deleteAttachmentIds.length > 0) {
        const attachmentsToDelete = await tx.query.techSalesAttachments.findMany({
          where: sql`${techSalesAttachments.id} IN (${deleteAttachmentIds.join(',')})`
        });

        for (const attachment of attachmentsToDelete) {
          // DB에서 레코드 삭제
          const [deletedAttachment] = await tx.delete(techSalesAttachments)
            .where(eq(techSalesAttachments.id, attachment.id))
            .returning();

          results.deleted.push(deletedAttachment);
          await deleteFile(attachment.filePath);
        }
      }

      // 2. 새 파일 업로드 처리
              if (newFiles.length > 0) {
          for (const { file, attachmentType, description } of newFiles) {
            const saveResult = await saveDRMFile(
              file,
              decryptWithServerAction,
              `techsales-rfq/${techSalesRfqId}`
            );

            if (!saveResult.success) {
              throw new Error(saveResult.error || "파일 저장에 실패했습니다.");
            }

          // DB에 첨부파일 레코드 생성
          const [newAttachment] = await tx.insert(techSalesAttachments).values({
            techSalesRfqId,
            attachmentType,
            fileName: saveResult.fileName!,
            originalFileName: file.name,
            filePath: saveResult.publicPath!,
            fileSize: file.size,
            fileType: file.type || undefined,
            description: description || undefined,
            createdBy,
          }).returning();

          results.uploaded.push(newAttachment);
        }
      }
    });



    // 캐시 무효화
    revalidateTag("techSalesRfqs");
    revalidateTag(`techSalesRfq-${techSalesRfqId}`);
    revalidatePath("/evcp/budgetary-tech-sales-ship");

    return { 
      data: results, 
      error: null,
      message: `${results.uploaded.length}개 업로드, ${results.deleted.length}개 삭제 완료`
    };
  } catch (err) {
    console.error("기술영업 RFQ 첨부파일 일괄 처리 오류:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

// ========================================
// 메일 발송 관련 함수들
// ========================================

/**
 * 벤더 견적 제출 확인 메일 발송 (벤더용)
 */
export async function sendQuotationSubmittedNotificationToVendor(quotationId: number) {
  try {
    // 견적서 정보 조회 (projectSeries 조인 추가)
    const quotation = await db.query.techSalesVendorQuotations.findFirst({
      where: eq(techSalesVendorQuotations.id, quotationId),
      with: {
        rfq: {
          with: {
            biddingProject: true,
            createdByUser: {
              columns: {
                id: true,
                name: true,
                email: true,
              }
            }
          }
        },
        vendor: {
          columns: {
            id: true,
            vendorName: true,
            vendorCode: true,
          }
        }
      }
    });

    if (!quotation || !quotation.rfq || !quotation.vendor) {
      console.error("견적서 또는 관련 정보를 찾을 수 없습니다");
      return { success: false, error: "견적서 정보를 찾을 수 없습니다" };
    }

    // 벤더 사용자들 조회
    const vendorUsers = await db.query.users.findMany({
      where: eq(users.companyId, quotation.vendor.id),
      columns: {
        id: true,
        email: true,
        name: true,
        language: true
      }
    });

    const vendorEmails = vendorUsers
      .filter(user => user.email)
      .map(user => user.email)
      .join(", ");

    if (!vendorEmails) {
      console.warn(`벤더 ID ${quotation.vendor.id}에 등록된 이메일 주소가 없습니다`);
      return { success: false, error: "벤더 이메일 주소가 없습니다" };
    }

    // RFQ 아이템 정보 조회
    const rfqItemsResult = await getTechSalesRfqItems(quotation.rfq.id);
    const rfqItems = rfqItemsResult.data || [];
    
    // 이메일 컨텍스트 구성 (시리즈 정보 제거, 프로젝트 정보 간소화)
    const emailContext = {
      language: vendorUsers[0]?.language || "ko",
      quotation: {
        id: quotation.id,
        currency: quotation.currency,
        totalPrice: quotation.totalPrice,
        validUntil: quotation.validUntil,
        submittedAt: quotation.submittedAt,
        remark: quotation.remark,
      },
      rfq: {
        id: quotation.rfq.id,
        code: quotation.rfq.rfqCode,
        title: quotation.rfq.description || '',
        projectCode: quotation.rfq.biddingProject?.pspid || '',
        projectName: quotation.rfq.biddingProject?.projNm || '',
        dueDate: quotation.rfq.dueDate,
        materialCode: quotation.rfq.materialCode,
        description: quotation.rfq.remark,
      },
      items: rfqItems.map(item => ({
        itemCode: item.itemCode,
        itemList: item.itemList,
        workType: item.workType,
        shipTypes: item.shipTypes,
        subItemList: item.subItemList,
        itemType: item.itemType,
      })),
      vendor: {
        id: quotation.vendor.id,
        code: quotation.vendor.vendorCode,
        name: quotation.vendor.vendorName,
      },
      project: {
        name: quotation.rfq.biddingProject?.projNm || '',
        sector: quotation.rfq.biddingProject?.sector || '',
        shipCount: quotation.rfq.biddingProject?.projMsrm ? Number(quotation.rfq.biddingProject.projMsrm) : 0,
        ownerName: quotation.rfq.biddingProject?.kunnrNm || '',
        className: quotation.rfq.biddingProject?.cls1Nm || '',
      },
      manager: {
        name: quotation.rfq.createdByUser?.name || '',
        email: quotation.rfq.createdByUser?.email || '',
      },
      systemUrl: process.env.NEXT_PUBLIC_APP_URL || 'http://60.101.108.100/ko/partners',
      companyName: 'Samsung Heavy Industries',
      year: new Date().getFullYear(),
    };

    // 이메일 발송
    await sendEmail({
      to: vendorEmails,
      subject: `[견적 제출 확인] ${quotation.rfq.rfqCode} - 견적 요청`,
      template: 'tech-sales-quotation-submitted-vendor-ko',
      context: emailContext,
    });

    console.log(`벤더 견적 제출 확인 메일 발송 완료: ${vendorEmails}`);
    return { success: true };
  } catch (error) {
    console.error("벤더 견적 제출 확인 메일 발송 오류:", error);
    return { success: false, error: "메일 발송 중 오류가 발생했습니다" };
  }
}

/**
 * 벤더 견적 접수 알림 메일 발송 (담당자용)
 */
export async function sendQuotationSubmittedNotificationToManager(quotationId: number) {
  try {
    // 견적서 정보 조회
    const quotation = await db.query.techSalesVendorQuotations.findFirst({
      where: eq(techSalesVendorQuotations.id, quotationId),
      with: {
        rfq: {
          with: {
            biddingProject: true,
            createdByUser: {
              columns: {
                id: true,
                name: true,
                email: true,
              }
            }
          }
        },
        vendor: {
          columns: {
            id: true,
            vendorName: true,
            vendorCode: true,
          }
        }
      }
    });

    if (!quotation || !quotation.rfq || !quotation.vendor) {
      console.error("견적서 또는 관련 정보를 찾을 수 없습니다");
      return { success: false, error: "견적서 정보를 찾을 수 없습니다" };
    }

    const manager = quotation.rfq.createdByUser;
    if (!manager?.email) {
      console.warn("담당자 이메일 주소가 없습니다");
      return { success: false, error: "담당자 이메일 주소가 없습니다" };
    }

    // RFQ 아이템 정보 조회
    const rfqItemsResult = await getTechSalesRfqItems(quotation.rfq.id);
    const rfqItems = rfqItemsResult.data || [];
    
    // 이메일 컨텍스트 구성 (시리즈 정보 제거, 프로젝트 정보 간소화)
    const emailContext = {
      language: "ko",
      quotation: {
        id: quotation.id,
        currency: quotation.currency,
        totalPrice: quotation.totalPrice,
        validUntil: quotation.validUntil,
        submittedAt: quotation.submittedAt,
        remark: quotation.remark,
      },
      rfq: {
        id: quotation.rfq.id,
        code: quotation.rfq.rfqCode,
        title: quotation.rfq.description || '',
        projectCode: quotation.rfq.biddingProject?.pspid || '',
        projectName: quotation.rfq.biddingProject?.projNm || '',
        dueDate: quotation.rfq.dueDate,
        materialCode: quotation.rfq.materialCode,
        description: quotation.rfq.remark,
      },
      items: rfqItems.map(item => ({
        itemCode: item.itemCode,
        itemList: item.itemList,
        workType: item.workType,
        shipTypes: item.shipTypes,
        subItemList: item.subItemList,
        itemType: item.itemType,
      })),
      vendor: {
        id: quotation.vendor.id,
        code: quotation.vendor.vendorCode,
        name: quotation.vendor.vendorName,
      },
      project: {
        name: quotation.rfq.biddingProject?.projNm || '',
        sector: quotation.rfq.biddingProject?.sector || '',
        shipCount: quotation.rfq.biddingProject?.projMsrm ? Number(quotation.rfq.biddingProject.projMsrm) : 0,
        ownerName: quotation.rfq.biddingProject?.kunnrNm || '',
        className: quotation.rfq.biddingProject?.cls1Nm || '',
      },
      manager: {
        name: manager.name || '',
        email: manager.email,
      },
      systemUrl: process.env.NEXT_PUBLIC_APP_URL || 'http://60.101.108.100/ko/evcp',
      companyName: 'Samsung Heavy Industries',
      year: new Date().getFullYear(),
    };

    // 이메일 발송
    await sendEmail({
      to: manager.email,
      subject: `[견적 접수 알림] ${quotation.vendor.vendorName}에서 ${quotation.rfq.rfqCode} 견적서를 제출했습니다`,
      template: 'tech-sales-quotation-submitted-manager-ko',
      context: emailContext,
    });

    console.log(`담당자 견적 접수 알림 메일 발송 완료: ${manager.email}`);
    return { success: true };
  } catch (error) {
    console.error("담당자 견적 접수 알림 메일 발송 오류:", error);
    return { success: false, error: "메일 발송 중 오류가 발생했습니다" };
  }
}

/**
 * 벤더 견적 선택 알림 메일 발송
 */
export async function sendQuotationAcceptedNotification(quotationId: number) {
  try {
    // 견적서 정보 조회
    const quotation = await db.query.techSalesVendorQuotations.findFirst({
      where: eq(techSalesVendorQuotations.id, quotationId),
      with: {
        rfq: {
          with: {
            biddingProject: true,
            createdByUser: {
              columns: {
                id: true,
                name: true,
                email: true,
              }
            }
          }
        },
        vendor: {
          columns: {
            id: true,
            vendorName: true,
            vendorCode: true,
          }
        }
      }
    });

    if (!quotation || !quotation.rfq || !quotation.vendor) {
      console.error("견적서 또는 관련 정보를 찾을 수 없습니다");
      return { success: false, error: "견적서 정보를 찾을 수 없습니다" };
    }

    // 벤더 사용자들 조회
    const vendorUsers = await db.query.users.findMany({
      where: eq(users.companyId, quotation.vendor.id),
      columns: {
        id: true,
        email: true,
        name: true,
        language: true
      }
    });

    const vendorEmails = vendorUsers
      .filter(user => user.email)
      .map(user => user.email)
      .join(", ");

    if (!vendorEmails) {
      console.warn(`벤더 ID ${quotation.vendor.id}에 등록된 이메일 주소가 없습니다`);
      return { success: false, error: "벤더 이메일 주소가 없습니다" };
    }

    // RFQ 아이템 정보 조회
    const rfqItemsResult = await getTechSalesRfqItems(quotation.rfq.id);
    const rfqItems = rfqItemsResult.data || [];
    
    // 이메일 컨텍스트 구성 (시리즈 정보 제거, 프로젝트 정보 간소화)
    const emailContext = {
      language: vendorUsers[0]?.language || "ko",
      quotation: {
        id: quotation.id,
        currency: quotation.currency,
        totalPrice: quotation.totalPrice,
        validUntil: quotation.validUntil,
        acceptedAt: quotation.acceptedAt,
        remark: quotation.remark,
      },
      rfq: {
        id: quotation.rfq.id,
        code: quotation.rfq.rfqCode,
        title: quotation.rfq.description || '',
        projectCode: quotation.rfq.biddingProject?.pspid || '',
        projectName: quotation.rfq.biddingProject?.projNm || '',
        dueDate: quotation.rfq.dueDate,
        materialCode: quotation.rfq.materialCode,
        description: quotation.rfq.remark,
      },
      items: rfqItems.map(item => ({
        itemCode: item.itemCode,
        itemList: item.itemList,
        workType: item.workType,
        shipTypes: item.shipTypes,
        subItemList: item.subItemList,
        itemType: item.itemType,
      })),
      vendor: {
        id: quotation.vendor.id,
        code: quotation.vendor.vendorCode,
        name: quotation.vendor.vendorName,
      },
      project: {
        name: quotation.rfq.biddingProject?.projNm || '',
        sector: quotation.rfq.biddingProject?.sector || '',
        shipCount: quotation.rfq.biddingProject?.projMsrm ? Number(quotation.rfq.biddingProject.projMsrm) : 0,
        ownerName: quotation.rfq.biddingProject?.kunnrNm || '',
        className: quotation.rfq.biddingProject?.cls1Nm || '',
      },
      manager: {
        name: quotation.rfq.createdByUser?.name || '',
        email: quotation.rfq.createdByUser?.email || '',
      },
      systemUrl: process.env.NEXT_PUBLIC_APP_URL || 'http://60.101.108.100/ko/partners',
      companyName: 'Samsung Heavy Industries',
      year: new Date().getFullYear(),
    };

    // 이메일 발송
    await sendEmail({
      to: vendorEmails,
      subject: `[견적 선택 알림] ${quotation.rfq.rfqCode} - 귀하의 견적이 선택되었습니다`,
      template: 'tech-sales-quotation-accepted-ko',
      context: emailContext,
    });

    console.log(`벤더 견적 선택 알림 메일 발송 완료: ${vendorEmails}`);
    return { success: true };
  } catch (error) {
    console.error("벤더 견적 선택 알림 메일 발송 오류:", error);
    return { success: false, error: "메일 발송 중 오류가 발생했습니다" };
  }
}

// ==================== Vendor Communication 관련 ====================

export interface TechSalesAttachment {
  id: number
  fileName: string
  fileSize: number
  fileType: string | null // <- null 허용
  filePath: string
  uploadedAt: Date
}

export interface TechSalesComment {
  id: number
  rfqId: number
  vendorId: number | null  // null 허용으로 변경
  userId?: number | null   // null 허용으로 변경
  content: string
  isVendorComment: boolean | null  // null 허용으로 변경
  createdAt: Date
  updatedAt: Date
  userName?: string | null  // null 허용으로 변경
  vendorName?: string | null  // null 허용으로 변경
  attachments: TechSalesAttachment[]
  isRead: boolean | null   // null 허용으로 변경
}

/**
 * 특정 RFQ의 벤더별 읽지 않은 메시지 개수를 조회하는 함수
 * 
 * @param rfqId RFQ ID
 * @returns 벤더별 읽지 않은 메시지 개수 (vendorId: count)
 */
export async function getTechSalesUnreadMessageCounts(rfqId: number): Promise<Record<number, number>> {
  try {
    // 벤더가 보낸 읽지 않은 메시지를 벤더별로 카운트
    const unreadCounts = await db
      .select({
        vendorId: techSalesRfqComments.vendorId,
        count: sql<number>`count(*)`,
      })
      .from(techSalesRfqComments)
      .where(
        and(
          eq(techSalesRfqComments.rfqId, rfqId),
          eq(techSalesRfqComments.isVendorComment, true), // 벤더가 보낸 메시지
          eq(techSalesRfqComments.isRead, false), // 읽지 않은 메시지
          sql`${techSalesRfqComments.vendorId} IS NOT NULL` // vendorId가 null이 아닌 것
        )
      )
      .groupBy(techSalesRfqComments.vendorId);

    // Record<number, number> 형태로 변환
    const result: Record<number, number> = {};
    unreadCounts.forEach(item => {
      if (item.vendorId) {
        result[item.vendorId] = item.count;
      }
    });

    return result;
  } catch (error) {
    console.error('techSales 읽지 않은 메시지 개수 조회 오류:', error);
    return {};
  }
}

/**
 * 특정 RFQ와 벤더 간의 커뮤니케이션 메시지를 가져오는 서버 액션
 * 
 * @param rfqId RFQ ID
 * @param vendorId 벤더 ID
 * @returns 코멘트 목록
 */
export async function fetchTechSalesVendorComments(rfqId: number, vendorId?: number): Promise<TechSalesComment[]> {
  if (!vendorId) {
    return []
  }

  try {
    // 인증 확인
    const session = await getServerSession(authOptions);

    if (!session?.user) {
      throw new Error("인증이 필요합니다")
    }

    // 코멘트 쿼리
    const comments = await db.query.techSalesRfqComments.findMany({
      where: and(
        eq(techSalesRfqComments.rfqId, rfqId),
        eq(techSalesRfqComments.vendorId, vendorId)
      ),
      orderBy: [techSalesRfqComments.createdAt],
      with: {
        user: {
          columns: {
            name: true
          }
        },
        vendor: {
          columns: {
            vendorName: true
          }
        },
        attachments: true,
      }
    })

    // 결과 매핑
    return comments.map(comment => ({
      id: comment.id,
      rfqId: comment.rfqId,
      vendorId: comment.vendorId,
      userId: comment.userId || undefined,
      content: comment.content,
      isVendorComment: comment.isVendorComment,
      createdAt: comment.createdAt,
      updatedAt: comment.updatedAt,
      userName: comment.user?.name,
      vendorName: comment.vendor?.vendorName,
      isRead: comment.isRead,
      attachments: comment.attachments.map(att => ({
        id: att.id,
        fileName: att.fileName,
        fileSize: att.fileSize,
        fileType: att.fileType,
        filePath: att.filePath,
        originalFileName: att.originalFileName,
        uploadedAt: att.uploadedAt
      }))
    }))
  } catch (error) {
    console.error('techSales 벤더 코멘트 가져오기 오류:', error)
    throw error
  }
}

/**
 * 코멘트를 읽음 상태로 표시하는 서버 액션
 * 
 * @param rfqId RFQ ID
 * @param vendorId 벤더 ID
 */
export async function markTechSalesMessagesAsRead(rfqId: number, vendorId?: number): Promise<void> {
  if (!vendorId) {
    return
  }

  try {
    // 인증 확인
    const session = await getServerSession(authOptions);

    if (!session?.user) {
      throw new Error("인증이 필요합니다")
    }

    // 벤더가 작성한 읽지 않은 코멘트 업데이트
    await db.update(techSalesRfqComments)
      .set({ isRead: true })
      .where(
        and(
          eq(techSalesRfqComments.rfqId, rfqId),
          eq(techSalesRfqComments.vendorId, vendorId),
          eq(techSalesRfqComments.isVendorComment, true),
          eq(techSalesRfqComments.isRead, false)
        )
      )

    // 캐시 무효화
    revalidateTag(`tech-sales-rfq-${rfqId}-comments`)
  } catch (error) {
    console.error('techSales 메시지 읽음 표시 오류:', error)
    throw error
  }
}

// ==================== RFQ 조선/해양 관련 ====================

/**
 * 기술영업 조선 RFQ 생성 (1:N 관계)
 */
export async function createTechSalesShipRfq(input: {
  biddingProjectId: number;
  itemIds: number[]; // 조선 아이템 ID 배열
  dueDate: Date;
  description?: string;
  createdBy: number;
}) {
  unstable_noStore();  
  try {
    return await db.transaction(async (tx) => {
      // 프로젝트 정보 조회 (유효성 검증)
      const biddingProject = await tx.query.biddingProjects.findFirst({
        where: (biddingProjects, { eq }) => eq(biddingProjects.id, input.biddingProjectId)
      });

      if (!biddingProject) {
        throw new Error(`프로젝트 ID ${input.biddingProjectId}를 찾을 수 없습니다.`);
      }

      // RFQ 코드 생성 (SHIP 타입)
      const rfqCode = await generateRfqCodes(tx, 1);
      
      // RFQ 생성
      const [rfq] = await tx
        .insert(techSalesRfqs)
        .values({
          rfqCode: rfqCode[0],
          biddingProjectId: input.biddingProjectId,
          description: input.description,
          dueDate: input.dueDate,
          status: "RFQ Created",
          rfqType: "SHIP",
          createdBy: input.createdBy,
          updatedBy: input.createdBy,
        })
        .returning({ id: techSalesRfqs.id });

      // 아이템들 추가
      for (const itemId of input.itemIds) {
        await tx
          .insert(techSalesRfqItems)
          .values({
            rfqId: rfq.id,
            itemShipbuildingId: itemId,
            itemType: "SHIP",
          });
      }

      // 캐시 무효화
      revalidateTag("techSalesRfqs");
      revalidatePath("/evcp/budgetary-tech-sales-ship");

      return { data: rfq, error: null };
    });
  } catch (err) {
    console.error("Error creating Ship RFQ:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 해양 Hull RFQ 생성 (1:N 관계)
 */
export async function createTechSalesHullRfq(input: {
  biddingProjectId: number;
  itemIds: number[]; // Hull 아이템 ID 배열
  dueDate: Date;
  description?: string;
  createdBy: number;
}) {
  unstable_noStore();
  console.log('🔍 createTechSalesHullRfq 호출됨:', input);
  
  try {
    return await db.transaction(async (tx) => {
      // 프로젝트 정보 조회 (유효성 검증)
      const biddingProject = await tx.query.biddingProjects.findFirst({
        where: (biddingProjects, { eq }) => eq(biddingProjects.id, input.biddingProjectId)
      });

      if (!biddingProject) {
        throw new Error(`프로젝트 ID ${input.biddingProjectId}를 찾을 수 없습니다.`);
      }

      // RFQ 코드 생성 (HULL 타입)
      const hullRfqCode = await generateRfqCodes(tx, 1);
      
      // RFQ 생성
      const [rfq] = await tx
        .insert(techSalesRfqs)
        .values({
          rfqCode: hullRfqCode[0],
          biddingProjectId: input.biddingProjectId,
          description: input.description,
          dueDate: input.dueDate,
          status: "RFQ Created",
          rfqType: "HULL",
          createdBy: input.createdBy,
          updatedBy: input.createdBy,
        })
        .returning({ id: techSalesRfqs.id });

      // 아이템들 추가
      for (const itemId of input.itemIds) {
        await tx
          .insert(techSalesRfqItems)
          .values({
            rfqId: rfq.id,
            itemOffshoreHullId: itemId,
            itemType: "HULL",
          });
      }

      // 캐시 무효화
      revalidateTag("techSalesRfqs");
      revalidatePath("/evcp/budgetary-tech-sales-hull");

      return { data: rfq, error: null };
    });
  } catch (err) {
    console.error("Error creating Hull RFQ:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 해양 TOP RFQ 생성 (1:N 관계)
 */
export async function createTechSalesTopRfq(input: {
  biddingProjectId: number;
  itemIds: number[]; // TOP 아이템 ID 배열
  dueDate: Date;
  description?: string;
  createdBy: number;
}) {
  unstable_noStore();
  console.log('🔍 createTechSalesTopRfq 호출됨:', input);
  
  try {
    return await db.transaction(async (tx) => {
      // 프로젝트 정보 조회 (유효성 검증)
      const biddingProject = await tx.query.biddingProjects.findFirst({
        where: (biddingProjects, { eq }) => eq(biddingProjects.id, input.biddingProjectId)
      });

      if (!biddingProject) {
        throw new Error(`프로젝트 ID ${input.biddingProjectId}를 찾을 수 없습니다.`);
      }

      // RFQ 코드 생성 (TOP 타입)
      const topRfqCode = await generateRfqCodes(tx, 1);
      
      // RFQ 생성
      const [rfq] = await tx
        .insert(techSalesRfqs)
        .values({
          rfqCode: topRfqCode[0],
          biddingProjectId: input.biddingProjectId,
          description: input.description,
          dueDate: input.dueDate,
          status: "RFQ Created",
          rfqType: "TOP",
          createdBy: input.createdBy,
          updatedBy: input.createdBy,
        })
        .returning({ id: techSalesRfqs.id });

      // 아이템들 추가
      for (const itemId of input.itemIds) {
        await tx
          .insert(techSalesRfqItems)
          .values({
            rfqId: rfq.id,
            itemOffshoreTopId: itemId,
            itemType: "TOP",
          });
      }

      // 캐시 무효화
      revalidateTag("techSalesRfqs");
      revalidatePath("/evcp/budgetary-tech-sales-top");

      return { data: rfq, error: null };
    });
  } catch (err) {
    console.error("Error creating TOP RFQ:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 조선 RFQ 전용 조회 함수 
 */
export async function getTechSalesShipRfqsWithJoin(input: GetTechSalesRfqsSchema) {
  return getTechSalesRfqsWithJoin({ ...input, rfqType: "SHIP" });
}

/**
 * 해양 TOP RFQ 전용 조회 함수
 */
export async function getTechSalesTopRfqsWithJoin(input: GetTechSalesRfqsSchema) {
  return getTechSalesRfqsWithJoin({ ...input, rfqType: "TOP" });
}

/**
 * 해양 HULL RFQ 전용 조회 함수
 */
export async function getTechSalesHullRfqsWithJoin(input: GetTechSalesRfqsSchema) {
  return getTechSalesRfqsWithJoin({ ...input, rfqType: "HULL" });
}

/**
 * 조선 벤더 견적서 전용 조회 함수
 */
export async function getTechSalesShipVendorQuotationsWithJoin(input: {
  rfqId?: number;
  vendorId?: number;
  search?: string;
  filters?: Filter<typeof techSalesVendorQuotations>[];
  sort?: { id: string; desc: boolean }[];
  page: number;
  perPage: number;
}) {
  return getTechSalesVendorQuotationsWithJoin({ ...input, rfqType: "SHIP" });
}

/**
 * 해양 TOP 벤더 견적서 전용 조회 함수
 */
export async function getTechSalesTopVendorQuotationsWithJoin(input: {
  rfqId?: number;
  vendorId?: number;
  search?: string;
  filters?: Filter<typeof techSalesVendorQuotations>[];
  sort?: { id: string; desc: boolean }[];
  page: number;
  perPage: number;
}) {
  return getTechSalesVendorQuotationsWithJoin({ ...input, rfqType: "TOP" });
}

/**
 * 해양 HULL 벤더 견적서 전용 조회 함수
 */
export async function getTechSalesHullVendorQuotationsWithJoin(input: {
  rfqId?: number;
  vendorId?: number;
  search?: string;
  filters?: Filter<typeof techSalesVendorQuotations>[];
  sort?: { id: string; desc: boolean }[];
  page: number;
  perPage: number;
}) {
  return getTechSalesVendorQuotationsWithJoin({ ...input, rfqType: "HULL" });
}

/** 
 * 기술영업 RFQ의 아이템 목록 조회
 */
export async function getTechSalesRfqItems(rfqId: number) {
  unstable_noStore();
  try {
    const items = await db.query.techSalesRfqItems.findMany({
      where: eq(techSalesRfqItems.rfqId, rfqId),
      with: {
        itemShipbuilding: {
          columns: {
            id: true,
            itemCode: true,
            itemList: true,
            workType: true,
            shipTypes: true,
          }
        },
        itemOffshoreTop: {
          columns: {
            id: true,
            itemCode: true,
            itemList: true,
            workType: true,
            subItemList: true,
          }
        },
        itemOffshoreHull: {
          columns: {
            id: true,
            itemCode: true,
            itemList: true,
            workType: true,
            subItemList: true,
          }
        }
      },
      orderBy: [techSalesRfqItems.id]
    });

    // 아이템 타입에 따라 정보 매핑
    const mappedItems = items.map(item => {
      let itemInfo = null;
      
      switch (item.itemType) {
        case 'SHIP':
          itemInfo = item.itemShipbuilding;
          break;
        case 'TOP':
          itemInfo = item.itemOffshoreTop;
          break;
        case 'HULL':
          itemInfo = item.itemOffshoreHull;
          break;
      }

      return {
        id: item.id,
        rfqId: item.rfqId,
        itemType: item.itemType,
        itemCode: itemInfo?.itemCode || '',
        itemList: itemInfo?.itemList || '',
        workType: itemInfo?.workType || '',
        // 조선이면 shipType, 해양이면 subItemList
        shipTypes: item.itemType === 'SHIP' ? (itemInfo as { shipTypes?: string })?.shipTypes || '' : undefined,
        subItemList: item.itemType !== 'SHIP' ? (itemInfo as { subItemList?: string })?.subItemList || '' : undefined,
      };
    });

    return { data: mappedItems, error: null };
  } catch (err) {
    console.error("Error fetching RFQ items:", err);
    return { data: [], error: getErrorMessage(err) };
  }
}

/**
 * RFQ 아이템들과 매칭되는 후보 벤더들을 찾는 함수
 */
export async function getTechSalesRfqCandidateVendors(rfqId: number) {
  unstable_noStore();
  
  try {
    return await db.transaction(async (tx) => {
      // 1. RFQ 정보 조회 (타입 확인)
      const rfq = await tx.query.techSalesRfqs.findFirst({
        where: eq(techSalesRfqs.id, rfqId),
        columns: {
          id: true,
          rfqType: true
        }
      });

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

      // 2. RFQ 아이템들 조회
      const rfqItems = await tx.query.techSalesRfqItems.findMany({
        where: eq(techSalesRfqItems.rfqId, rfqId),
        with: {
          itemShipbuilding: true,
          itemOffshoreTop: true,
          itemOffshoreHull: true,
        }
      });

      if (rfqItems.length === 0) {
        return { data: [], error: null };
      }

      // 3. 아이템 ID들 추출 (타입별로)
      const shipItemIds: number[] = [];
      const topItemIds: number[] = [];
      const hullItemIds: number[] = [];
      
      rfqItems.forEach(item => {
        if (item.itemType === "SHIP" && item.itemShipbuilding?.id) {
          shipItemIds.push(item.itemShipbuilding.id);
        } else if (item.itemType === "TOP" && item.itemOffshoreTop?.id) {
          topItemIds.push(item.itemOffshoreTop.id);
        } else if (item.itemType === "HULL" && item.itemOffshoreHull?.id) {
          hullItemIds.push(item.itemOffshoreHull.id);
        }
      });

      if (shipItemIds.length === 0 && topItemIds.length === 0 && hullItemIds.length === 0) {
        return { data: [], error: null };
      }

      // 4. 각 타입별로 매칭되는 벤더들 조회
      const candidateVendorsMap = new Map();

      // 조선 아이템 매칭 벤더들
      if (shipItemIds.length > 0) {
        const shipVendors = await tx
          .select({
            id: techVendors.id,
            vendorId: techVendors.id,
            vendorName: techVendors.vendorName,
            vendorCode: techVendors.vendorCode,
            country: techVendors.country,
            email: techVendors.email,
            phone: techVendors.phone,
            status: techVendors.status,
            techVendorType: techVendors.techVendorType,
            matchedItemCode: itemShipbuilding.itemCode,
          })
          .from(techVendorPossibleItems)
          .innerJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .innerJoin(itemShipbuilding, eq(techVendorPossibleItems.shipbuildingItemId, itemShipbuilding.id))
          .where(
            and(
              inArray(techVendorPossibleItems.shipbuildingItemId, shipItemIds),
              or(
                eq(techVendors.status, "ACTIVE"),
                eq(techVendors.status, "QUOTE_COMPARISON")
              )
            )
          );

        shipVendors.forEach(vendor => {
          const key = vendor.vendorId;
          if (!candidateVendorsMap.has(key)) {
            candidateVendorsMap.set(key, {
              ...vendor,
              matchedItemCodes: [],
              matchedItemCount: 0
            });
          }
          candidateVendorsMap.get(key).matchedItemCodes.push(vendor.matchedItemCode);
          candidateVendorsMap.get(key).matchedItemCount++;
        });
      }

      // 해양 TOP 아이템 매칭 벤더들
      if (topItemIds.length > 0) {
        const topVendors = await tx
          .select({
            id: techVendors.id,
            vendorId: techVendors.id,
            vendorName: techVendors.vendorName,
            vendorCode: techVendors.vendorCode,
            country: techVendors.country,
            email: techVendors.email,
            phone: techVendors.phone,
            status: techVendors.status,
            techVendorType: techVendors.techVendorType,
            matchedItemCode: itemOffshoreTop.itemCode,
          })
          .from(techVendorPossibleItems)
          .innerJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .innerJoin(itemOffshoreTop, eq(techVendorPossibleItems.offshoreTopItemId, itemOffshoreTop.id))
          .where(
            and(
              inArray(techVendorPossibleItems.offshoreTopItemId, topItemIds),
              or(
                eq(techVendors.status, "ACTIVE"),
                eq(techVendors.status, "QUOTE_COMPARISON")
              )
            )
          );

        topVendors.forEach(vendor => {
          const key = vendor.vendorId;
          if (!candidateVendorsMap.has(key)) {
            candidateVendorsMap.set(key, {
              ...vendor,
              matchedItemCodes: [],
              matchedItemCount: 0
            });
          }
          candidateVendorsMap.get(key).matchedItemCodes.push(vendor.matchedItemCode);
          candidateVendorsMap.get(key).matchedItemCount++;
        });
      }

      // 해양 HULL 아이템 매칭 벤더들
      if (hullItemIds.length > 0) {
        const hullVendors = await tx
          .select({
            id: techVendors.id,
            vendorId: techVendors.id,
            vendorName: techVendors.vendorName,
            vendorCode: techVendors.vendorCode,
            country: techVendors.country,
            email: techVendors.email,
            phone: techVendors.phone,
            status: techVendors.status,
            techVendorType: techVendors.techVendorType,
            matchedItemCode: itemOffshoreHull.itemCode,
          })
          .from(techVendorPossibleItems)
          .innerJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
          .innerJoin(itemOffshoreHull, eq(techVendorPossibleItems.offshoreHullItemId, itemOffshoreHull.id))
          .where(
            and(
              inArray(techVendorPossibleItems.offshoreHullItemId, hullItemIds),
              or(
                eq(techVendors.status, "ACTIVE"),
                eq(techVendors.status, "QUOTE_COMPARISON")
              )
            )
          );

        hullVendors.forEach(vendor => {
          const key = vendor.vendorId;
          if (!candidateVendorsMap.has(key)) {
            candidateVendorsMap.set(key, {
              ...vendor,
              matchedItemCodes: [],
              matchedItemCount: 0
            });
          }
          candidateVendorsMap.get(key).matchedItemCodes.push(vendor.matchedItemCode);
          candidateVendorsMap.get(key).matchedItemCount++;
        });
      }

      // 5. 결과 정렬 (매칭된 아이템 수 기준 내림차순)
      const candidateVendors = Array.from(candidateVendorsMap.values())
        .sort((a, b) => b.matchedItemCount - a.matchedItemCount);

      return { data: candidateVendors, error: null };
    });
  } catch (err) {
    console.error("Error fetching candidate vendors:", err);
    return { data: [], error: getErrorMessage(err) };
  }
}

/**
 * RFQ 타입에 따른 캐시 무효화 경로 반환
 */
function getTechSalesRevalidationPath(rfqType: "SHIP" | "TOP" | "HULL"): string {
  switch (rfqType) {
    case "SHIP":
      return "/evcp/budgetary-tech-sales-ship";
    case "TOP":
      return "/evcp/budgetary-tech-sales-top";
    case "HULL":
      return "/evcp/budgetary-tech-sales-hull";
    default:
      return "/evcp/budgetary-tech-sales-ship";
  }
}

/**
 * 기술영업 RFQ에 여러 벤더 추가 (techVendors 기반)
 * 벤더 추가 시에는 견적서를 생성하지 않고, RFQ 전송 시에 견적서를 생성
 */
export async function addTechVendorsToTechSalesRfq(input: {
  rfqId: number;
  vendorIds: number[];
  vendorFlags?: Record<string, {
    isCustomerPreferred?: boolean;
    isNewDiscovery?: boolean;
    isProjectApproved?: boolean;
    isShiProposal?: boolean;
  }>;
  createdBy: number;
}) {
  unstable_noStore();
  
  try {
    return await db.transaction(async (tx) => {
      const results = [];
      const errors: string[] = [];

      // 1. RFQ 상태 및 타입 확인
      const rfq = await tx.query.techSalesRfqs.findFirst({
        where: eq(techSalesRfqs.id, input.rfqId),
        columns: {
          id: true,
          status: true,
          rfqType: true,
        }
      });

      if (!rfq) {
        throw new Error("RFQ를 찾을 수 없습니다");
      }
      
      // 2. 각 벤더에 대해 처리 (이미 추가된 벤더는 견적서가 있는지 확인)
      for (const vendorId of input.vendorIds) {
        try {
          // 이미 추가된 벤더인지 확인 (견적서 존재 여부로 확인)
          const existingQuotation = await tx.query.techSalesVendorQuotations.findFirst({
            where: and(
              eq(techSalesVendorQuotations.rfqId, input.rfqId),
              eq(techSalesVendorQuotations.vendorId, vendorId)
            )
          });

          if (existingQuotation) {
            errors.push(`벤더 ID ${vendorId}는 이미 추가되어 있습니다.`);
            continue;
          }

          // 벤더가 실제로 존재하는지 확인
          const vendor = await tx.query.techVendors.findFirst({
            where: eq(techVendors.id, vendorId),
            columns: { id: true, vendorName: true }
          });

          if (!vendor) {
            errors.push(`벤더 ID ${vendorId}를 찾을 수 없습니다.`);
            continue;
          }

          // 🔥 중요: 벤더 추가 시에는 견적서를 생성하지 않고, "Assigned" 상태로만 생성
          // quotation_version은 null로 설정하여 벤더가 실제 견적 제출 시에만 리비전 생성
          const [quotation] = await tx
            .insert(techSalesVendorQuotations)
            .values({
              rfqId: input.rfqId,
              vendorId: vendorId,
              status: "Assigned", // Draft가 아닌 Assigned 상태로 생성
              quotationVersion: null, // 리비전은 견적 제출 시에만 생성
              vendorFlags: input.vendorFlags?.[vendorId.toString()] || null, // 벤더 구분자 정보 추가
              createdBy: input.createdBy,
              updatedBy: input.createdBy,
            })
            .returning({ id: techSalesVendorQuotations.id });

          // 🆕 RFQ의 아이템들을 tech_vendor_possible_items에 추가
          try {
            // RFQ의 아이템들 조회
            const rfqItemsResult = await getTechSalesRfqItems(input.rfqId);

            if (rfqItemsResult.data && rfqItemsResult.data.length > 0) {
              for (const item of rfqItemsResult.data) {
                let vendorPossibleItem = null;
                // 조선: 아이템코드 + 선종으로 조선아이템테이블에서 찾기, 해양: 아이템코드로만 찾기
                if (item.itemType === "SHIP" && item.itemCode && item.shipTypes) {
                  // 조선: itemShipbuilding에서 itemCode, shipTypes로 찾기
                  const shipbuildingItem = await tx.query.itemShipbuilding.findFirst({
                    where: and(
                      eq(itemShipbuilding.itemCode, item.itemCode),
                      eq(itemShipbuilding.shipTypes, item.shipTypes)
                    )
                  });
                  if (shipbuildingItem?.id) {
                    vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
                      where: and(
                        eq(techVendorPossibleItems.vendorId, vendorId),
                        eq(techVendorPossibleItems.shipbuildingItemId, shipbuildingItem.id)
                      )
                    });
                    
                    if (!vendorPossibleItem) {
                      await tx.insert(techVendorPossibleItems).values({
                        vendorId: vendorId,
                        shipbuildingItemId: shipbuildingItem.id,
                      });
                    }
                  }
                } else if (item.itemType === "TOP" && item.itemCode) {
                  // 해양 TOP: itemOffshoreTop에서 itemCode로 찾기
                  const offshoreTopItem = await tx.query.itemOffshoreTop.findFirst({
                    where: eq(itemOffshoreTop.itemCode, item.itemCode)
                  });
                  if (offshoreTopItem?.id) {
                    vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
                      where: and(
                        eq(techVendorPossibleItems.vendorId, vendorId),
                        eq(techVendorPossibleItems.offshoreTopItemId, offshoreTopItem.id)
                      )
                    });
                    
                    if (!vendorPossibleItem) {
                      await tx.insert(techVendorPossibleItems).values({
                        vendorId: vendorId,
                        offshoreTopItemId: offshoreTopItem.id,
                      });
                    }
                  }
                } else if (item.itemType === "HULL" && item.itemCode) {
                  // 해양 HULL: itemOffshoreHull에서 itemCode로 찾기
                  const offshoreHullItem = await tx.query.itemOffshoreHull.findFirst({
                    where: eq(itemOffshoreHull.itemCode, item.itemCode)
                  });
                  if (offshoreHullItem?.id) {
                    vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
                      where: and(
                        eq(techVendorPossibleItems.vendorId, vendorId),
                        eq(techVendorPossibleItems.offshoreHullItemId, offshoreHullItem.id)
                      )
                    });
                    
                    if (!vendorPossibleItem) {
                      await tx.insert(techVendorPossibleItems).values({
                        vendorId: vendorId,
                        offshoreHullItemId: offshoreHullItem.id,
                      });
                    }
                  }
                }
              }
            }
          } catch (possibleItemError) {
            // tech_vendor_possible_items 추가 실패는 전체 실패로 처리하지 않음
            console.warn(`벤더 ${vendorId}의 가능 아이템 추가 실패:`, possibleItemError);
          }

          results.push({ id: quotation.id, vendorId, vendorName: vendor.vendorName });
        } catch (vendorError) {
          console.error(`Error adding vendor ${vendorId}:`, vendorError);
          errors.push(`벤더 ID ${vendorId} 추가 중 오류가 발생했습니다.`);
        }
      }

      // 3. RFQ 상태가 "RFQ Created"이고 성공적으로 추가된 벤더가 있는 경우 상태 업데이트
      if (rfq.status === "RFQ Created" && results.length > 0) {
        await tx.update(techSalesRfqs)
          .set({
            status: "RFQ Vendor Assignned",
            updatedBy: input.createdBy,
            updatedAt: new Date()
          })
          .where(eq(techSalesRfqs.id, input.rfqId));
      }

      // 캐시 무효화 (RFQ 타입에 따른 동적 경로)
      revalidateTag("techSalesRfqs");
      revalidateTag("techSalesVendorQuotations");
      revalidateTag(`techSalesRfq-${input.rfqId}`);
      revalidatePath(getTechSalesRevalidationPath(rfq.rfqType || "SHIP"));

      return { 
        data: results, 
        error: errors.length > 0 ? errors.join(", ") : null,
        successCount: results.length,
        errorCount: errors.length
      };
    });
  } catch (err) {
    console.error("Error adding tech vendors to RFQ:", err);
    return { data: [], error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 RFQ의 벤더 목록 조회 (techVendors 기반)
 */
export async function getTechSalesRfqTechVendors(rfqId: number) {
  unstable_noStore();
  
  try {
    return await db.transaction(async (tx) => {
      const vendors = await tx
        .select({
          id: techSalesVendorQuotations.id,
          vendorId: techVendors.id,
          vendorName: techVendors.vendorName,
          vendorCode: techVendors.vendorCode,
          country: techVendors.country,
          email: techVendors.email,
          phone: techVendors.phone,
          status: techSalesVendorQuotations.status,
          totalPrice: techSalesVendorQuotations.totalPrice,
          currency: techSalesVendorQuotations.currency,
          validUntil: techSalesVendorQuotations.validUntil,
          submittedAt: techSalesVendorQuotations.submittedAt,
          createdAt: techSalesVendorQuotations.createdAt,
        })
        .from(techSalesVendorQuotations)
        .innerJoin(techVendors, eq(techSalesVendorQuotations.vendorId, techVendors.id))
        .where(eq(techSalesVendorQuotations.rfqId, rfqId))
        .orderBy(desc(techSalesVendorQuotations.createdAt));

      return { data: vendors, error: null };
    });
  } catch (err) {
    console.error("Error fetching RFQ tech vendors:", err);
    return { data: [], error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 RFQ에서 기술영업 벤더 제거 (techVendors 기반)
 */
export async function removeTechVendorFromTechSalesRfq(input: {
  rfqId: number;
  vendorId: number;
}) {
  unstable_noStore();
  
  try {
    return await db.transaction(async (tx) => {
      // 해당 벤더의 견적서 상태 확인
      const existingQuotation = await tx.query.techSalesVendorQuotations.findFirst({
        where: and(
          eq(techSalesVendorQuotations.rfqId, input.rfqId),
          eq(techSalesVendorQuotations.vendorId, input.vendorId)
        )
      });

      if (!existingQuotation) {
        return { data: null, error: "해당 벤더가 이 RFQ에 존재하지 않습니다." };
      }

      // Assigned 상태가 아닌 경우 삭제 불가
      if (existingQuotation.status !== "Assigned") {
        return { data: null, error: "Assigned 상태의 벤더만 삭제할 수 있습니다." };
      }

      // 해당 벤더의 견적서 삭제
      const [deletedQuotation] = await tx
        .delete(techSalesVendorQuotations)
        .where(
          and(
            eq(techSalesVendorQuotations.rfqId, input.rfqId),
            eq(techSalesVendorQuotations.vendorId, input.vendorId)
          )
        )
        .returning({ id: techSalesVendorQuotations.id });

      // 캐시 무효화
      revalidateTag("techSalesRfqs");
      revalidateTag("techSalesVendorQuotations");

      return { data: deletedQuotation, error: null };
    });
  } catch (err) {
    console.error("Error removing tech vendor from RFQ:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 RFQ에서 여러 기술영업 벤더 제거 (techVendors 기반)
 */
export async function removeTechVendorsFromTechSalesRfq(input: {
  rfqId: number;
  vendorIds: number[];
}) {
  unstable_noStore();
  
  try {
    return await db.transaction(async (tx) => {
      const results = [];
      const errors: string[] = [];

      for (const vendorId of input.vendorIds) {
        // 해당 벤더의 견적서 상태 확인
        const existingQuotation = await tx.query.techSalesVendorQuotations.findFirst({
          where: and(
            eq(techSalesVendorQuotations.rfqId, input.rfqId),
            eq(techSalesVendorQuotations.vendorId, vendorId)
          )
        });

        if (!existingQuotation) {
          errors.push(`벤더 ID ${vendorId}가 이 RFQ에 존재하지 않습니다.`);
          continue;
        }

        // Assigned 상태가 아닌 경우 삭제 불가
        if (existingQuotation.status !== "Assigned") {
          errors.push(`벤더 ID ${vendorId}는 Assigned 상태가 아니므로 삭제할 수 없습니다.`);
          continue;
        }

        // 해당 벤더의 견적서 삭제
        const [deletedQuotation] = await tx
          .delete(techSalesVendorQuotations)
          .where(
            and(
              eq(techSalesVendorQuotations.rfqId, input.rfqId),
              eq(techSalesVendorQuotations.vendorId, vendorId)
            )
          )
          .returning({ id: techSalesVendorQuotations.id });

        results.push(deletedQuotation);
      }

      // 캐시 무효화
      revalidateTag("techSalesRfqs");
      revalidateTag("techSalesVendorQuotations");

      return { 
        data: results, 
        error: errors.length > 0 ? errors.join(", ") : null,
        successCount: results.length,
        errorCount: errors.length
      };
    });
  } catch (err) {
    console.error("Error removing tech vendors from RFQ:", err);
    return { data: [], error: getErrorMessage(err) };
  }
}

/**
 * 기술영업 벤더 검색
 */
export async function searchTechVendors(searchTerm: string, limit = 100, rfqType?: "SHIP" | "TOP" | "HULL") {
  unstable_noStore();
  
  try {
    // RFQ 타입에 따른 벤더 타입 매핑
    const vendorTypeFilter = rfqType === "SHIP" ? "조선" : 
                            rfqType === "TOP" ? "해양TOP" :
                            rfqType === "HULL" ? "해양HULL" : null;

    const whereConditions = [
      or(
        eq(techVendors.status, "ACTIVE"),
        eq(techVendors.status, "QUOTE_COMPARISON")
      ),
      or(
        ilike(techVendors.vendorName, `%${searchTerm}%`),
        ilike(techVendors.vendorCode, `%${searchTerm}%`)
      )
    ];

    // RFQ 타입이 지정된 경우 벤더 타입 필터링 추가 (컴마 구분 문자열에서 검색)
    if (vendorTypeFilter) {
      whereConditions.push(sql`${techVendors.techVendorType} LIKE ${'%' + vendorTypeFilter + '%'}`);
    }

    const results = await db
      .select({
        id: techVendors.id,
        vendorName: techVendors.vendorName,
        vendorCode: techVendors.vendorCode,
        status: techVendors.status,
        country: techVendors.country,
        techVendorType: techVendors.techVendorType,
      })
      .from(techVendors)
      .where(and(...whereConditions))
      .limit(limit)
      .orderBy(techVendors.vendorName);

    return results;
  } catch (err) {
    console.error("Error searching tech vendors:", err);
    throw new Error(getErrorMessage(err));
  }
}


/**
 * 벤더 견적서 거절 처리 (벤더가 직접 거절)
 */
export async function rejectTechSalesVendorQuotations(input: {
  quotationIds: number[];
  rejectionReason?: string;
}) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      throw new Error("인증이 필요합니다.");
    }

    const result = await db.transaction(async (tx) => {
      // 견적서들이 존재하고 벤더가 권한이 있는지 확인
      const quotations = await tx
        .select({
          id: techSalesVendorQuotations.id,
          status: techSalesVendorQuotations.status,
          vendorId: techSalesVendorQuotations.vendorId,
        })
        .from(techSalesVendorQuotations)
        .where(inArray(techSalesVendorQuotations.id, input.quotationIds));

      if (quotations.length !== input.quotationIds.length) {
        throw new Error("일부 견적서를 찾을 수 없습니다.");
      }

      // 이미 거절된 견적서가 있는지 확인
      const alreadyRejected = quotations.filter(q => q.status === "Rejected");
      if (alreadyRejected.length > 0) {
        throw new Error("이미 거절된 견적서가 포함되어 있습니다.");
      }

      // 승인된 견적서가 있는지 확인
      const alreadyAccepted = quotations.filter(q => q.status === "Accepted");
      if (alreadyAccepted.length > 0) {
        throw new Error("이미 승인된 견적서는 거절할 수 없습니다.");
      }

      // 견적서 상태를 거절로 변경
      await tx
        .update(techSalesVendorQuotations)
        .set({
          status: "Rejected",
          rejectionReason: input.rejectionReason || null,
          updatedBy: parseInt(session.user.id),
          updatedAt: new Date(),
        })
        .where(inArray(techSalesVendorQuotations.id, input.quotationIds));

      return { success: true, updatedCount: quotations.length };
    });
    revalidateTag("techSalesRfqs");
    revalidateTag("techSalesVendorQuotations");
    revalidatePath("/partners/techsales/rfq-ship", "page");
    return { 
      success: true, 
      message: `${result.updatedCount}개의 견적서가 거절되었습니다.`,
      data: result
    };
  } catch (error) {
    console.error("견적서 거절 오류:", error);
    return { 
      success: false, 
      error: getErrorMessage(error) 
    };
  }
}

// ==================== Revision 관련 ====================

/**
 * 견적서 revision 히스토리 조회
 */
export async function getTechSalesVendorQuotationRevisions(quotationId: number) {
  try {
    const revisions = await db
      .select({
        id: techSalesVendorQuotationRevisions.id,
        version: techSalesVendorQuotationRevisions.version,
        snapshot: techSalesVendorQuotationRevisions.snapshot,
        changeReason: techSalesVendorQuotationRevisions.changeReason,
        revisionNote: techSalesVendorQuotationRevisions.revisionNote,
        revisedBy: techSalesVendorQuotationRevisions.revisedBy,
        revisedAt: techSalesVendorQuotationRevisions.revisedAt,
        // 수정자 정보 조인
        revisedByName: users.name,
      })
      .from(techSalesVendorQuotationRevisions)
      .leftJoin(users, eq(techSalesVendorQuotationRevisions.revisedBy, users.id))
      .where(eq(techSalesVendorQuotationRevisions.quotationId, quotationId))
      .orderBy(desc(techSalesVendorQuotationRevisions.version));

    return { data: revisions, error: null };
  } catch (error) {
    console.error("견적서 revision 히스토리 조회 오류:", error);
    return { data: null, error: "견적서 히스토리를 조회하는 중 오류가 발생했습니다." };
  }
}

/**
 * 견적서의 현재 버전과 revision 히스토리를 함께 조회 (각 리비전의 첨부파일 포함)
 */
export async function getTechSalesVendorQuotationWithRevisions(quotationId: number) {
  try {
    // 먼저 현재 견적서 조회
    const currentQuotation = await db.query.techSalesVendorQuotations.findFirst({
      where: eq(techSalesVendorQuotations.id, quotationId),
      with: {
        // 벤더 정보와 RFQ 정보도 함께 조회 (필요한 경우)
      }
    });

    if (!currentQuotation) {
      return { data: null, error: "견적서를 찾을 수 없습니다." };
    }

    // 이제 현재 견적서의 정보를 알고 있으므로 병렬로 나머지 정보 조회
    const [revisionsResult, currentAttachments] = await Promise.all([
      getTechSalesVendorQuotationRevisions(quotationId),
      getTechSalesVendorQuotationAttachmentsByRevision(quotationId, currentQuotation.quotationVersion || 0)
    ]);

    // 현재 견적서에 첨부파일 정보 추가
    const currentWithAttachments = {
      ...currentQuotation,
      attachments: currentAttachments.data || []
    };

    // 각 리비전의 첨부파일 정보 추가
    const revisionsWithAttachments = await Promise.all(
      (revisionsResult.data || []).map(async (revision) => {
        const attachmentsResult = await getTechSalesVendorQuotationAttachmentsByRevision(quotationId, revision.version);
        return {
          ...revision,
          attachments: attachmentsResult.data || []
        };
      })
    );

    return {
      data: {
        current: currentWithAttachments,
        revisions: revisionsWithAttachments
      },
      error: null
    };
  } catch (error) {
    console.error("견적서 전체 히스토리 조회 오류:", error);
    return { data: null, error: "견적서 정보를 조회하는 중 오류가 발생했습니다." };
  }
}

/**
 * 견적서 첨부파일 조회 (리비전 ID 기준 오름차순 정렬)
 */
export async function getTechSalesVendorQuotationAttachments(quotationId: number) {
  return unstable_cache(
    async () => {
      try {
        const attachments = await db
          .select({
            id: techSalesVendorQuotationAttachments.id,
            quotationId: techSalesVendorQuotationAttachments.quotationId,
            revisionId: techSalesVendorQuotationAttachments.revisionId,
            fileName: techSalesVendorQuotationAttachments.fileName,
            originalFileName: techSalesVendorQuotationAttachments.originalFileName,
            fileSize: techSalesVendorQuotationAttachments.fileSize,
            fileType: techSalesVendorQuotationAttachments.fileType,
            filePath: techSalesVendorQuotationAttachments.filePath,
            description: techSalesVendorQuotationAttachments.description,
            uploadedBy: techSalesVendorQuotationAttachments.uploadedBy,
            vendorId: techSalesVendorQuotationAttachments.vendorId,
            isVendorUpload: techSalesVendorQuotationAttachments.isVendorUpload,
            createdAt: techSalesVendorQuotationAttachments.createdAt,
            updatedAt: techSalesVendorQuotationAttachments.updatedAt,
          })
          .from(techSalesVendorQuotationAttachments)
          .where(eq(techSalesVendorQuotationAttachments.quotationId, quotationId))
          .orderBy(desc(techSalesVendorQuotationAttachments.createdAt));

        return { data: attachments };
      } catch (error) {
        console.error("견적서 첨부파일 조회 오류:", error);
        return { error: "견적서 첨부파일 조회 중 오류가 발생했습니다." };
      }
    },
    [`quotation-attachments-${quotationId}`],
    {
      revalidate: 60,
      tags: [`quotation-${quotationId}`, "quotation-attachments"],
    }
  )();
}

/**
 * 특정 리비전의 견적서 첨부파일 조회
 */
export async function getTechSalesVendorQuotationAttachmentsByRevision(quotationId: number, revisionId: number) {
  try {
    const attachments = await db
      .select({
        id: techSalesVendorQuotationAttachments.id,
        quotationId: techSalesVendorQuotationAttachments.quotationId,
        revisionId: techSalesVendorQuotationAttachments.revisionId,
        fileName: techSalesVendorQuotationAttachments.fileName,
        originalFileName: techSalesVendorQuotationAttachments.originalFileName,
        fileSize: techSalesVendorQuotationAttachments.fileSize,
        fileType: techSalesVendorQuotationAttachments.fileType,
        filePath: techSalesVendorQuotationAttachments.filePath,
        description: techSalesVendorQuotationAttachments.description,
        uploadedBy: techSalesVendorQuotationAttachments.uploadedBy,
        vendorId: techSalesVendorQuotationAttachments.vendorId,
        isVendorUpload: techSalesVendorQuotationAttachments.isVendorUpload,
        createdAt: techSalesVendorQuotationAttachments.createdAt,
        updatedAt: techSalesVendorQuotationAttachments.updatedAt,
      })
      .from(techSalesVendorQuotationAttachments)
      .where(and(
        eq(techSalesVendorQuotationAttachments.quotationId, quotationId),
        eq(techSalesVendorQuotationAttachments.revisionId, revisionId)
      ))
      .orderBy(desc(techSalesVendorQuotationAttachments.createdAt));

    return { data: attachments };
  } catch (error) {
    console.error("리비전별 견적서 첨부파일 조회 오류:", error);
    return { error: "첨부파일 조회 중 오류가 발생했습니다." };
  }
}


// ==================== Project AVL 관련 ====================

/**
 * Accepted 상태의 Tech Sales Vendor Quotations 조회 (RFQ, Vendor 정보 포함)
 */
export async function getAcceptedTechSalesVendorQuotations(input: {
  search?: string;
  filters?: Filter<typeof techSalesVendorQuotations>[];
  sort?: { id: string; desc: boolean }[];
  page: number;
  perPage: number;
  rfqType?: "SHIP" | "TOP" | "HULL";
}) {
  unstable_noStore();
  
  try {
    const offset = (input.page - 1) * input.perPage;
    
    // 기본 WHERE 조건: status = 'Accepted'만 조회, rfqType이 'SHIP'이 아닌 것만
    const baseConditions = [or(
      eq(techSalesVendorQuotations.status, 'Submitted'),
      eq(techSalesVendorQuotations.status, 'Accepted')
    )
    ];
    
    // 검색 조건 추가
    const searchConditions = [];
    if (input.search) {
      searchConditions.push(
        ilike(techSalesRfqs.rfqCode, `%${input.search}%`),
        ilike(techSalesRfqs.description, `%${input.search}%`),
        ilike(sql`vendors.vendor_name`, `%${input.search}%`),
        ilike(sql`vendors.vendor_code`, `%${input.search}%`)
      );
    }

    // 정렬 조건 변환
    const orderByConditions: OrderByType[] = [];
    if (input.sort?.length) {
      input.sort.forEach((sortItem) => {
        switch (sortItem.id) {
          case "rfqCode":
            orderByConditions.push(sortItem.desc ? desc(techSalesRfqs.rfqCode) : asc(techSalesRfqs.rfqCode));
            break;
          case "description":
            orderByConditions.push(sortItem.desc ? desc(techSalesRfqs.description) : asc(techSalesRfqs.description));
            break;
          case "vendorName":
            orderByConditions.push(sortItem.desc ? desc(sql`vendors.vendor_name`) : asc(sql`vendors.vendor_name`));
            break;
          case "vendorCode":
            orderByConditions.push(sortItem.desc ? desc(sql`vendors.vendor_code`) : asc(sql`vendors.vendor_code`));
            break;
          case "totalPrice":
            orderByConditions.push(sortItem.desc ? desc(techSalesVendorQuotations.totalPrice) : asc(techSalesVendorQuotations.totalPrice));
            break;
          case "acceptedAt":
            orderByConditions.push(sortItem.desc ? desc(techSalesVendorQuotations.acceptedAt) : asc(techSalesVendorQuotations.acceptedAt));
            break;
          default:
            orderByConditions.push(desc(techSalesVendorQuotations.acceptedAt));
        }
      });
    } else {
      orderByConditions.push(desc(techSalesVendorQuotations.acceptedAt));
    }

    // 필터 조건 추가
    const filterConditions = [];
    if (input.filters?.length) {
      const filterWhere = filterColumns({
        table: techSalesVendorQuotations,
        filters: input.filters,
        joinOperator: "and",
      });
      if (filterWhere) {  
        filterConditions.push(filterWhere);
      }
    }

    // RFQ 타입 필터
    if (input.rfqType) {
      filterConditions.push(eq(techSalesRfqs.rfqType, input.rfqType));
    }

    // 모든 조건 결합
    const allConditions = [
      ...baseConditions,
      ...filterConditions,
      ...(searchConditions.length > 0 ? [or(...searchConditions)] : [])
    ];

    const whereCondition = allConditions.length > 1 
      ? and(...allConditions) 
      : allConditions[0];

    // 데이터 조회
    const data = await db
      .select({
        // Quotation 정보
        id: techSalesVendorQuotations.id,
        rfqId: techSalesVendorQuotations.rfqId,
        vendorId: techSalesVendorQuotations.vendorId,
        quotationCode: techSalesVendorQuotations.quotationCode,
        quotationVersion: techSalesVendorQuotations.quotationVersion,
        totalPrice: techSalesVendorQuotations.totalPrice,
        currency: techSalesVendorQuotations.currency,
        validUntil: techSalesVendorQuotations.validUntil,
        status: techSalesVendorQuotations.status,
        remark: techSalesVendorQuotations.remark,
        submittedAt: techSalesVendorQuotations.submittedAt,
        acceptedAt: techSalesVendorQuotations.acceptedAt,
        createdAt: techSalesVendorQuotations.createdAt,
        updatedAt: techSalesVendorQuotations.updatedAt,
        
        // RFQ 정보
        rfqCode: techSalesRfqs.rfqCode,
        rfqType: techSalesRfqs.rfqType,
        description: techSalesRfqs.description,
        dueDate: techSalesRfqs.dueDate,
        rfqStatus: techSalesRfqs.status,
        materialCode: techSalesRfqs.materialCode,
        
        // Vendor 정보
        vendorName: sql<string>`vendors.vendor_name`,
        vendorCode: sql<string | null>`vendors.vendor_code`,
        vendorEmail: sql<string | null>`vendors.email`,
        vendorCountry: sql<string | null>`vendors.country`,
        
        // Project 정보
        projNm: biddingProjects.projNm,
        pspid: biddingProjects.pspid,
        sector: biddingProjects.sector,
      })
      .from(techSalesVendorQuotations)
      .leftJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id))
      .leftJoin(sql`vendors`, eq(techSalesVendorQuotations.vendorId, sql`vendors.id`))
      .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id))
      .where(whereCondition)
      .orderBy(...orderByConditions)
      .limit(input.perPage)
      .offset(offset);

    // 총 개수 조회
    const totalCount = await db
      .select({ count: count() })
      .from(techSalesVendorQuotations)
      .leftJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id))
      .leftJoin(sql`vendors`, eq(techSalesVendorQuotations.vendorId, sql`vendors.id`))
      .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id))
      .where(whereCondition);

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

    return {
      data,
      pageCount,
      total,
    };

  } catch (error) {
    console.error("getAcceptedTechSalesVendorQuotations 오류:", error);
    throw new Error(`Accepted quotations 조회 실패: ${getErrorMessage(error)}`);
  }
}

export async function getBidProjects(pjtType: 'SHIP' | 'TOP' | 'HULL'): Promise<Project[]> {
  try {
    // 트랜잭션을 사용하여 프로젝트 데이터 조회
    const projectList = await db.transaction(async (tx) => {
      // 기본 쿼리 구성
      const query = tx
        .select({
          id: biddingProjects.id,
          projectCode: biddingProjects.pspid,
          projectName: biddingProjects.projNm,
          pjtType: biddingProjects.pjtType,
        })
        .from(biddingProjects)
        .where(eq(biddingProjects.pjtType, pjtType));
      
      const results = await query.orderBy(biddingProjects.id);
      return results;
    });
    
    // Handle null projectName values and ensure pjtType is not null
    const validProjectList = projectList.map(project => ({
      ...project,
      projectName: project.projectName || '', // Replace null with empty string
      pjtType: project.pjtType as "SHIP" | "TOP" | "HULL" // Type assertion since WHERE filters ensure non-null
    }));

    return validProjectList;
  } catch (error) {
    console.error("프로젝트 목록 가져오기 실패:", error);
    return []; // 오류 발생 시 빈 배열 반환
  }
}

/**
 * 여러 벤더의 contact 정보 조회
 */
export async function getTechVendorsContacts(vendorIds: number[]) {
  unstable_noStore();
  try {
    // 직접 조인으로 벤더와 contact 정보 조회
    const contactsWithVendor = await db
      .select({
        contactId: techVendorContacts.id,
        contactName: techVendorContacts.contactName,
        contactPosition: techVendorContacts.contactPosition,
        contactTitle: techVendorContacts.contactTitle,
        contactEmail: techVendorContacts.contactEmail,
        contactPhone: techVendorContacts.contactPhone,
        isPrimary: techVendorContacts.isPrimary,
        vendorId: techVendorContacts.vendorId,
        vendorName: techVendors.vendorName,
        vendorCode: techVendors.vendorCode
      })
      .from(techVendorContacts)
      .leftJoin(techVendors, eq(techVendorContacts.vendorId, techVendors.id))
      .where(inArray(techVendorContacts.vendorId, vendorIds))
      .orderBy(
        asc(techVendorContacts.vendorId),
        desc(techVendorContacts.isPrimary),
        asc(techVendorContacts.contactName)
      );

    // 벤더별로 그룹화
    const contactsByVendor = contactsWithVendor.reduce((acc, row) => {
      const vendorId = row.vendorId;
      if (!acc[vendorId]) {
        acc[vendorId] = {
          vendor: {
            id: vendorId,
            vendorName: row.vendorName || '',
            vendorCode: row.vendorCode || ''
          },
          contacts: []
        };
      }
      acc[vendorId].contacts.push({
        id: row.contactId,
        contactName: row.contactName,
        contactPosition: row.contactPosition,
        contactTitle: row.contactTitle,
        contactEmail: row.contactEmail,
        contactPhone: row.contactPhone,
        isPrimary: row.isPrimary
      });
      return acc;
    }, {} as Record<number, {
      vendor: {
        id: number;
        vendorName: string;
        vendorCode: string | null;
      };
      contacts: Array<{
        id: number;
        contactName: string;
        contactPosition: string | null;
        contactTitle: string | null;
        contactEmail: string;
        contactPhone: string | null;
        isPrimary: boolean;
      }>;
    }>);

    return { data: contactsByVendor, error: null };
  } catch (err) {
    console.error("벤더 contact 조회 오류:", err);
    return { data: {}, error: getErrorMessage(err) };
  }
}

/**
 * quotation별 발송된 담당자 정보 조회
 */
export async function getQuotationContacts(quotationId: number) {
  unstable_noStore();
  try {
    // quotation에 연결된 담당자들 조회
    const quotationContacts = await db
      .select({
        id: techSalesVendorQuotationContacts.id,
        contactId: techSalesVendorQuotationContacts.contactId,
        contactName: techVendorContacts.contactName,
        contactPosition: techVendorContacts.contactPosition,
        contactEmail: techVendorContacts.contactEmail,
        contactPhone: techVendorContacts.contactPhone,
        contactCountry: techVendorContacts.contactCountry,
        isPrimary: techVendorContacts.isPrimary,
        createdAt: techSalesVendorQuotationContacts.createdAt,
      })
      .from(techSalesVendorQuotationContacts)
      .innerJoin(
        techVendorContacts,
        eq(techSalesVendorQuotationContacts.contactId, techVendorContacts.id)
      )
      .where(eq(techSalesVendorQuotationContacts.quotationId, quotationId))
      .orderBy(techSalesVendorQuotationContacts.createdAt);

    return {
      success: true,
      data: quotationContacts,
      error: null,
    };
  } catch (error) {
    console.error("Quotation contacts 조회 오류:", error);
    return {
      success: false,
      data: [],
      error: getErrorMessage(error),
    };
  }
}

/**
 * 견적서 첨부파일 업로드 (클라이언트용)
 */
export async function uploadQuotationAttachments(
  quotationId: number,
  files: File[],
  userId: number
): Promise<{ success: boolean; attachments?: Array<{ fileName: string; originalFileName: string; filePath: string; fileSize: number }>; error?: string }> {
  try {
    const uploadedAttachments = [];

    for (const file of files) {
      const saveResult = await saveFile({
        file,
        directory: `techsales-quotations/${quotationId}`,
        userId: userId.toString(),
      });

      if (!saveResult.success) {
        throw new Error(saveResult.error || '파일 저장에 실패했습니다.');
      }

      uploadedAttachments.push({
        fileName: saveResult.fileName!, // 해시된 파일명 (저장용)
        originalFileName: saveResult.originalName!, // 원본 파일명 (표시용)
        filePath: saveResult.publicPath!,
        fileSize: file.size,
      });
    }

    return {
      success: true,
      attachments: uploadedAttachments
    };
  } catch (error) {
    console.error('견적서 첨부파일 업로드 오류:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : '파일 업로드 중 오류가 발생했습니다.'
    };
  }
}

/**
 * Update SHI Comment (revisionNote) for the current revision of a quotation.
 * Only the revisionNote is updated in the tech_sales_vendor_quotation_revisions table.
 */
export async function updateSHIComment(revisionId: number, revisionNote: string) {
  try {
    const updatedRevision = await db
      .update(techSalesVendorQuotationRevisions)
      .set({
        revisionNote: revisionNote,
      })
      .where(eq(techSalesVendorQuotationRevisions.id, revisionId))
      .returning();
      
    if (updatedRevision.length === 0) {
      return { data: null, error: "revision을 업데이트할 수 없습니다." };
    }
    
    return { data: updatedRevision[0], error: null };
  } catch (error) {
    console.error("SHI Comment 업데이트 중 오류:", error);
    return { data: null, error: "SHI Comment 업데이트 중 오류가 발생했습니다." };
  }
}

// RFQ 단일 조회 함수 추가
export async function getTechSalesRfqById(id: number) {
  try {
    const rfq = await db.query.techSalesRfqs.findFirst({
      where: eq(techSalesRfqs.id, id),
    });
    const project = await db
      .select({
        id: biddingProjects.id,
        projectCode: biddingProjects.pspid,
        projectName: biddingProjects.projNm,
        pjtType: biddingProjects.pjtType,
        ptypeNm: biddingProjects.ptypeNm,
        projMsrm: biddingProjects.projMsrm,
      })
        .from(biddingProjects)
        .where(eq(biddingProjects.id, rfq?.biddingProjectId ?? 0));
    
    if (!rfq) {
      return { data: null, error: "RFQ를 찾을 수 없습니다." };
    }
    
    return { data: { ...rfq, project }, error: null };
  } catch (err) {
    console.error("Error fetching RFQ:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}

// RFQ 업데이트 함수 수정 (description으로 통일)
export async function updateTechSalesRfq(data: {
  id: number;
  description: string;
  dueDate: Date;
  updatedBy: number;
}) {
  try {
    return await db.transaction(async (tx) => {
      const rfq = await tx.query.techSalesRfqs.findFirst({
        where: eq(techSalesRfqs.id, data.id),
      });
      
      if (!rfq) {
        return { data: null, error: "RFQ를 찾을 수 없습니다." };
      }
      
      const [updatedRfq] = await tx
        .update(techSalesRfqs)
        .set({
          description: data.description, // description 필드로 업데이트
          dueDate: data.dueDate,
          updatedAt: new Date(),
        })
        .where(eq(techSalesRfqs.id, data.id))
        .returning();
      
      revalidateTag("techSalesRfqs");
      revalidatePath(getTechSalesRevalidationPath(rfq.rfqType || "SHIP"));
      
      return { data: updatedRfq, error: null };
    });
  } catch (err) {
    console.error("Error updating RFQ:", err);
    return { data: null, error: getErrorMessage(err) };
  }
}