summaryrefslogtreecommitdiff
path: root/lib/vendor-investigation/service.ts
blob: 5e53d0dd88de4af992c1159757f4d4fc890b458a (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
"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택)

import { items, vendorInvestigationAttachments, vendorInvestigations, vendorInvestigationsView, vendorPossibleItems, vendors, siteVisitRequests, vendorPQSubmissions, users } from "@/db/schema/"
import { GetVendorsInvestigationSchema, updateVendorInvestigationSchema, updateVendorInvestigationProgressSchema, updateVendorInvestigationResultSchema } from "./validations"
import { asc, desc, ilike, inArray, and, or, gte, lte, eq, isNull, count } from "drizzle-orm";
import { revalidateTag, unstable_noStore, revalidatePath } from "next/cache";
import { filterColumns } from "@/lib/filter-columns";
import { unstable_cache } from "@/lib/unstable-cache";
import { getErrorMessage } from "@/lib/handle-error";
import db from "@/db/db";
import { sendEmail } from "../mail/sendEmail";
import fs from "fs"
import path from "path"
import { v4 as uuid } from "uuid"
import { vendorsLogs } from "@/db/schema";
import { cache } from "react"
import { deleteFile } from "../file-stroage";
import { saveDRMFile } from "../file-stroage";
import { decryptWithServerAction } from "@/components/drm/drmUtils";
import { format, addDays } from "date-fns";

export async function getVendorsInvestigation(input: GetVendorsInvestigationSchema) {
  try {
    const offset = (input.page - 1) * input.perPage

    // 1) Advanced filters
    const advancedWhere = filterColumns({
      table: vendorInvestigationsView,
      filters: input.filters,
      joinOperator: input.joinOperator,
    })

    // 2) Global search
    let globalWhere
    if (input.search) {
      const s = `%${input.search}%`
      globalWhere = or(
        // 협력업체 정보
        ilike(vendorInvestigationsView.vendorName, s),
        ilike(vendorInvestigationsView.vendorCode, s),

        // 담당자 정보 (새로 추가)
        ilike(vendorInvestigationsView.requesterName, s),
        ilike(vendorInvestigationsView.qmManagerName, s),

        // 실사 정보
        ilike(vendorInvestigationsView.investigationNotes, s),
        ilike(vendorInvestigationsView.investigationStatus, s),
        ilike(vendorInvestigationsView.investigationAddress, s),
        ilike(vendorInvestigationsView.investigationMethod, s),

        // 평가 결과
        ilike(vendorInvestigationsView.evaluationResult, s)
      )
    }
    // 3) Combine finalWhere
    const finalWhere = and(
      advancedWhere,
      globalWhere
    )

    // 4) Sorting
    const orderBy =
      input.sort && input.sort.length > 0
        ? input.sort.map((item) =>
            item.desc
              ? desc(vendorInvestigationsView[item.id])
              : asc(vendorInvestigationsView[item.id])
          )
        : [desc(vendorInvestigationsView.createdAt)]

    // 5) Query & count
    const { data, total } = await db.transaction(async (tx) => {
      // a) Select from the view
      const investigationsData = await tx
        .select()
        .from(vendorInvestigationsView)
        .where(finalWhere)
        .orderBy(...orderBy)
        .offset(offset)
        .limit(input.perPage)

      // b) Count total
      const resCount = await tx
        .select({ count: count() })
        .from(vendorInvestigationsView)
        .where(finalWhere)

      return { data: investigationsData, total: resCount[0]?.count }
    })

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

    // Data is already in the correct format from the simplified view
    return { data, pageCount }
  } catch (err) {
    console.error(err)
    return { data: [], pageCount: 0 }
  }
}
/**
 * Get existing investigations for a list of vendor IDs
 * 
 * @param vendorIds Array of vendor IDs to check for existing investigations
 * @returns Array of investigation data
 */
export async function getExistingInvestigationsForVendors(vendorIds: number[]) {
  if (!vendorIds.length) return []

  try {
    // Query the vendorInvestigationsView using the vendorIds
    const investigations = await db.query.vendorInvestigations.findMany({
      where: inArray(vendorInvestigationsView.vendorId, vendorIds),
      orderBy: [desc(vendorInvestigationsView.createdAt)],
    })

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

// PQ 제출 타입 조회 (investigation.pqSubmissionId → type)
export default async function getPQSubmissionTypeAction(pqSubmissionId: number) {
  try {
    const row = await db
      .select({ type: vendorPQSubmissions.type })
      .from(vendorPQSubmissions)
      .where(eq(vendorPQSubmissions.id, pqSubmissionId))
      .limit(1)
      .then(rows => rows[0]);
    if (!row) return { success: false, error: "PQ submission not found" };
    return { success: true, type: row.type as "GENERAL" | "PROJECT" | "NON_INSPECTION" };
  } catch (e) {
    return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
  }
}

// 실사 계획 취소 액션: 상태를 QM_REVIEW_CONFIRMED로 되돌림
export async function cancelInvestigationPlanAction(investigationId: number) {
  try {
    await db
      .update(vendorInvestigations)
      .set({
        investigationStatus: "QM_REVIEW_CONFIRMED",
        updatedAt: new Date(),
      })
      .where(eq(vendorInvestigations.id, investigationId))

    revalidateTag("vendor-investigations")
    revalidatePath("/evcp/vendor-investigation")

    return { success: true }
  } catch (error) {
    console.error("실사 계획 취소 오류:", error)
    return {
      success: false,
      error: error instanceof Error ? error.message : "알 수 없는 오류",
    }
  }
}

interface RequestInvestigateVendorsInput {
  ids: number[]
}

export async function requestInvestigateVendors({
  ids, userId // userId를 추가
}: RequestInvestigateVendorsInput & { userId: number }) {
  try {
    if (!ids || ids.length === 0) {
      return { error: "No vendor IDs provided." }
    }

    const result = await db.transaction(async (tx) => {
      // 1. Create a new investigation row for each vendor
      const newRecords = await tx
        .insert(vendorInvestigations)
        .values(
          ids.map((vendorId) => ({
            vendorId
          }))
        )
        .returning();

      // 2. 각 벤더에 대해 로그 기록
      await Promise.all(
        ids.map(async (vendorId) => {
          await tx.insert(vendorsLogs).values({
            vendorId: vendorId,
            userId: userId,
            action: "investigation_requested",
            comment: "Investigation requested for this vendor",
          });
        })
      );

      return newRecords;
    });

    // 3. 이메일 발송 (트랜잭션 외부에서 실행)
    await sendEmail({
      to: "dujin.kim@dtsolution.io",
      subject: "New Vendor Investigation(s) Requested",
      template: "investigation-request",
      context: {
        language: "ko",
        vendorIds: ids,
        notes: "Please initiate the planned investigations soon."
      },
    });

    // 4. 캐시 무효화
    revalidateTag("vendors");
    revalidateTag("vendor-investigations");

    return { data: result, error: null }
  } catch (err: unknown) {
    const errorMessage = err instanceof Error ? err.message : String(err)
    return { error: errorMessage }
  }
}


// 실사 진행 관리 업데이트 액션 (PLANNED -> IN_PROGRESS)
export async function updateVendorInvestigationProgressAction(formData: FormData) {
  try {
    // 1) 텍스트 필드만 추출
    const textEntries: Record<string, string> = {}
    for (const [key, value] of formData.entries()) {
      if (typeof value === "string") {
        textEntries[key] = value
      }
    }

    // 2) 적절한 타입으로 변환
    const processedEntries: any = {}
    
    // 필수 필드
    if (textEntries.investigationId) {
      processedEntries.investigationId = Number(textEntries.investigationId)
    }

    // 선택적 필드들
    if (textEntries.investigationAddress) {
      processedEntries.investigationAddress = textEntries.investigationAddress
    }
    if (textEntries.investigationMethod) {
      processedEntries.investigationMethod = textEntries.investigationMethod
    }

    // 선택적 날짜 필드
    if (textEntries.forecastedAt) {
      processedEntries.forecastedAt = new Date(textEntries.forecastedAt)
    }
    if (textEntries.confirmedAt) {
      processedEntries.confirmedAt = new Date(textEntries.confirmedAt)
    }

    // 3) Zod로 파싱/검증 (4개 필수값 규칙 포함)
    const parsed = updateVendorInvestigationProgressSchema.parse(processedEntries)

    // 4) 업데이트 데이터 준비
    const updateData: any = {
      updatedAt: new Date(),
    }

    // 선택적 필드들은 존재할 때만 추가
    if (parsed.investigationAddress !== undefined) {
      updateData.investigationAddress = parsed.investigationAddress
    }
    if (parsed.investigationMethod !== undefined) {
      updateData.investigationMethod = parsed.investigationMethod
    }
    if (parsed.forecastedAt !== undefined) {
      updateData.forecastedAt = parsed.forecastedAt
    }
    if (parsed.confirmedAt !== undefined) {
      updateData.confirmedAt = parsed.confirmedAt
    }

    // 실사 방법이 설정되면 QM_REVIEW_CONFIRMED -> IN_PROGRESS로 상태 변경
    if (parsed.investigationMethod) {
      updateData.investigationStatus = "IN_PROGRESS"
    }

    // 5) vendor_investigations 테이블 업데이트
    await db
      .update(vendorInvestigations)
      .set(updateData)
      .where(eq(vendorInvestigations.id, parsed.investigationId))

    // 6) 캐시 무효화
    revalidateTag("vendor-investigations")
    revalidatePath("/evcp/vendor-investigation")

    return { success: true }
  } catch (error) {
    console.error("실사 진행 관리 업데이트 오류:", error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "알 수 없는 오류" 
    }
  }
}

// 실사 결과 입력 액션 (IN_PROGRESS -> COMPLETED/CANCELED/SUPPLEMENT_REQUIRED)
export async function updateVendorInvestigationResultAction(formData: FormData) {
  try {
    // 1) 텍스트 필드만 추출
    const textEntries: Record<string, string> = {}
    for (const [key, value] of formData.entries()) {
      if (typeof value === "string") {
        textEntries[key] = value
      }
    }

    // 2) 적절한 타입으로 변환
    const processedEntries: any = {}
    
    // 필수 필드
    if (textEntries.investigationId) {
      processedEntries.investigationId = Number(textEntries.investigationId)
    }

    // 선택적 필드들
    if (textEntries.completedAt) {
      processedEntries.completedAt = new Date(textEntries.completedAt)
    }
    if (textEntries.evaluationScore) {
      processedEntries.evaluationScore = Number(textEntries.evaluationScore)
    }
    if (textEntries.evaluationResult) {
      processedEntries.evaluationResult = textEntries.evaluationResult
    }
    if (textEntries.investigationNotes) {
      processedEntries.investigationNotes = textEntries.investigationNotes
    }

    // attachments는 별도로 업로드되므로 빈 배열로 설정
    processedEntries.attachments = []

    // 3) Zod로 파싱/검증
    const parsed = updateVendorInvestigationResultSchema.parse(processedEntries)

    // 4) 업데이트 데이터 준비
    const updateData: any = {
      updatedAt: new Date(),
    }

    // 선택적 필드들은 존재할 때만 추가
    if (parsed.completedAt !== undefined) {
      updateData.completedAt = parsed.completedAt
    }
    if (parsed.evaluationScore !== undefined) {
      updateData.evaluationScore = parsed.evaluationScore
    }
    if (parsed.evaluationResult !== undefined) {
      updateData.evaluationResult = parsed.evaluationResult
    }
    if (parsed.investigationNotes !== undefined) {
      updateData.investigationNotes = parsed.investigationNotes
    }

    // 평가 결과에 따라 상태 자동 변경
    if (parsed.evaluationResult) {
      if (parsed.evaluationResult === "REJECTED") {
        updateData.investigationStatus = "CANCELED"
      } else if (parsed.evaluationResult === "SUPPLEMENT" ||
                 parsed.evaluationResult === "SUPPLEMENT_REINSPECT" ||
                 parsed.evaluationResult === "SUPPLEMENT_DOCUMENT") {
        updateData.investigationStatus = "SUPPLEMENT_REQUIRED"
        // 보완 요청이 있었음을 기록
        updateData.hasSupplementRequested = true
      } else if (parsed.evaluationResult === "APPROVED") {
        updateData.investigationStatus = "COMPLETED"
      }
    }

    // 5) vendor_investigations 테이블 업데이트
    await db
      .update(vendorInvestigations)
      .set(updateData)
      .where(eq(vendorInvestigations.id, parsed.investigationId))
    /*
    현재 보완-서류제출 프로세스는 자동으로 처리됨. 만약 dialog 필요하면 아래 서버액션 분기 필요.(1029/최겸)
    */
    // 5-1) 보완 프로세스 자동 처리 (TO-BE)
    if (parsed.evaluationResult === "SUPPLEMENT_REINSPECT" || parsed.evaluationResult === "SUPPLEMENT_DOCUMENT") {
      // 실사 방법 확인
      const investigation = await db
        .select({
          investigationMethod: vendorInvestigations.investigationMethod,
        })
        .from(vendorInvestigations)
        .where(eq(vendorInvestigations.id, parsed.investigationId))
        .then(rows => rows[0]);

      if (investigation?.investigationMethod === "PRODUCT_INSPECTION" || investigation?.investigationMethod === "SITE_VISIT_EVAL") {
       if (parsed.evaluationResult === "SUPPLEMENT_DOCUMENT") {
          // 보완-서류제출 요청 자동 생성
          await requestSupplementDocumentAction({
            investigationId: parsed.investigationId,
            documentRequests: {
              requiredDocuments: ["보완 서류"],
              additionalRequests: "보완을 위한 서류 제출 요청입니다.",
            }
          });
        }
      }
    }

    // 6) 캐시 무효화
    revalidateTag("vendor-investigations")
    revalidatePath("/evcp/vendor-investigation")
    revalidatePath("/evcp/pq_new")

    return { success: true }
  } catch (error) {
    console.error("실사 결과 업데이트 오류:", error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "알 수 없는 오류" 
    }
  }
}

// 기존 함수 (호환성을 위해 유지)
export async function updateVendorInvestigationAction(formData: FormData) {
  try {
    // 1) 텍스트 필드만 추출
    const textEntries: Record<string, string> = {}
    for (const [key, value] of formData.entries()) {
      if (typeof value === "string") {
        textEntries[key] = value
      }
    }

    // 2) 적절한 타입으로 변환
    const processedEntries: any = {}
    
    // 필수 필드
    if (textEntries.investigationId) {
      processedEntries.investigationId = Number(textEntries.investigationId)
    }
    if (textEntries.investigationStatus) {
      processedEntries.investigationStatus = textEntries.investigationStatus
    }

    // 선택적 enum 필드
    if (textEntries.investigationMethod) {
      processedEntries.investigationMethod = textEntries.investigationMethod
    }

    // 선택적 문자열 필드
    if (textEntries.investigationAddress) {
      processedEntries.investigationAddress = textEntries.investigationAddress
    }
    if (textEntries.investigationMethod) {
      processedEntries.investigationMethod = textEntries.investigationMethod
    }
    if (textEntries.investigationNotes) {
      processedEntries.investigationNotes = textEntries.investigationNotes
    }

    // 선택적 날짜 필드
    if (textEntries.forecastedAt) {
      processedEntries.forecastedAt = new Date(textEntries.forecastedAt)
    }
    if (textEntries.requestedAt) {
      processedEntries.requestedAt = new Date(textEntries.requestedAt)
    }
    if (textEntries.confirmedAt) {
      processedEntries.confirmedAt = new Date(textEntries.confirmedAt)
    }
    if (textEntries.completedAt) {
      processedEntries.completedAt = new Date(textEntries.completedAt)
    }

    // 선택적 숫자 필드
    if (textEntries.evaluationScore) {
      processedEntries.evaluationScore = Number(textEntries.evaluationScore)
    }

    // 선택적 평가 결과
    if (textEntries.evaluationResult) {
      processedEntries.evaluationResult = textEntries.evaluationResult
    }

    // 3) Zod로 파싱/검증
    const parsed = updateVendorInvestigationSchema.parse(processedEntries)

    // 4) 업데이트 데이터 준비 - 실제로 제공된 필드만 포함
    const updateData: any = {
      investigationStatus: parsed.investigationStatus,
      updatedAt: new Date(),
    }

    // 선택적 필드들은 존재할 때만 추가
    if (parsed.investigationMethod !== undefined) {
      updateData.investigationMethod = parsed.investigationMethod
    }
    if (parsed.investigationAddress !== undefined) {
      updateData.investigationAddress = parsed.investigationAddress
    }
    if (parsed.investigationMethod !== undefined) {
      updateData.investigationMethod = parsed.investigationMethod
    }
    if (parsed.forecastedAt !== undefined) {
      updateData.forecastedAt = parsed.forecastedAt
    }
    if (parsed.requestedAt !== undefined) {
      updateData.requestedAt = parsed.requestedAt
    }
    if (parsed.confirmedAt !== undefined) {
      updateData.confirmedAt = parsed.confirmedAt
    }
    if (parsed.completedAt !== undefined) {
      updateData.completedAt = parsed.completedAt
    }
    if (parsed.evaluationScore !== undefined) {
      updateData.evaluationScore = parsed.evaluationScore
    }
    if (parsed.evaluationResult !== undefined) {
      updateData.evaluationResult = parsed.evaluationResult
    }
    if (parsed.investigationNotes !== undefined) {
      updateData.investigationNotes = parsed.investigationNotes
    }
    // evaluationType이 null이 아니고, status가 계획중(PLANNED) 이라면, 진행중(IN_PROGRESS)으로 바꿔주는 로직 추가
    if (parsed.evaluationResult !== null && parsed.investigationStatus === "PLANNED") {
      updateData.investigationStatus = "IN_PROGRESS";
    }

    // 보완 프로세스 분기 로직 (TO-BE)
    if (parsed.evaluationResult === "SUPPLEMENT_REINSPECT" || parsed.evaluationResult === "SUPPLEMENT_DOCUMENT") {
      updateData.investigationStatus = "SUPPLEMENT_REQUIRED";
    }

    // 5) vendor_investigations 테이블 업데이트
    await db
      .update(vendorInvestigations)
      .set(updateData)
      .where(eq(vendorInvestigations.id, parsed.investigationId))

    // 5-1) 보완 프로세스 자동 처리 (TO-BE)
    if (parsed.evaluationResult === "SUPPLEMENT_REINSPECT" || parsed.evaluationResult === "SUPPLEMENT_DOCUMENT") {
      // 실사 방법 확인
      const investigation = await db
        .select({
          investigationMethod: vendorInvestigations.investigationMethod,
        })
        .from(vendorInvestigations)
        .where(eq(vendorInvestigations.id, parsed.investigationId))
        .then(rows => rows[0]);

      if (investigation?.investigationMethod === "PRODUCT_INSPECTION" || investigation?.investigationMethod === "SITE_VISIT_EVAL") {
        if (parsed.evaluationResult === "SUPPLEMENT_REINSPECT") {
          // 보완-재실사 요청 자동 생성
          await requestSupplementReinspectionAction({
            investigationId: parsed.investigationId,
            siteVisitData: {
              inspectionDuration: 1.0, // 기본 1일
              additionalRequests: "보완을 위한 재실사 요청입니다.",
            }
          });
        } else if (parsed.evaluationResult === "SUPPLEMENT_DOCUMENT") {
          // 보완-서류제출 요청 자동 생성
          await requestSupplementDocumentAction({
            investigationId: parsed.investigationId,
            documentRequests: {
              requiredDocuments: ["보완 서류"],
              additionalRequests: "보완을 위한 서류 제출 요청입니다.",
            }
          });
        }
      }
    }

    // 6) 캐시 무효화
    revalidateTag("vendor-investigations")
    revalidateTag("pq-submissions")
    revalidateTag("vendor-pq-submissions")
    revalidatePath("/evcp/pq_new")

    return { data: "OK", error: null }
  } catch (err: unknown) {
    console.error("Investigation update error:", err)
    const message = err instanceof Error ? err.message : String(err)
    return { error: message }
  }
}
// 실사 첨부파일 조회 함수
export async function getInvestigationAttachments(investigationId: number) {
  try {
    const attachments = await db
      .select()
      .from(vendorInvestigationAttachments)
      .where(eq(vendorInvestigationAttachments.investigationId, investigationId))
      .orderBy(vendorInvestigationAttachments.createdAt)

    return { success: true, attachments }
  } catch (error) {
    console.error("첨부파일 조회 실패:", error)
    return { success: false, error: "첨부파일 조회에 실패했습니다.", attachments: [] }
  }
}

// 첨부파일 삭제 함수
export async function deleteInvestigationAttachment(attachmentId: number) {
  try {
    // 파일 정보 조회
    const [attachment] = await db
      .select()
      .from(vendorInvestigationAttachments)
      .where(eq(vendorInvestigationAttachments.id, attachmentId))
      .limit(1)

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

    await deleteFile(attachment.filePath)

    // 데이터베이스에서 레코드 삭제
    await db
      .delete(vendorInvestigationAttachments)
      .where(eq(vendorInvestigationAttachments.id, attachmentId))

    // 캐시 무효화
    revalidateTag("vendor-investigations")
    
    return { success: true }
  } catch (error) {
    console.error("첨부파일 삭제 실패:", error)
    return { success: false, error: "첨부파일 삭제에 실패했습니다." }
  }
}

// 첨부파일 다운로드 정보 조회
export async function getAttachmentDownloadInfo(attachmentId: number) {
  try {
    const [attachment] = await db
      .select({
        fileName: vendorInvestigationAttachments.fileName,
        filePath: vendorInvestigationAttachments.filePath,
        mimeType: vendorInvestigationAttachments.mimeType,
        fileSize: vendorInvestigationAttachments.fileSize,
      })
      .from(vendorInvestigationAttachments)
      .where(eq(vendorInvestigationAttachments.id, attachmentId))
      .limit(1)

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

  
    return { 
      success: true, 
      downloadInfo: {
        fileName: attachment.fileName,
        filePath: attachment.filePath,
        mimeType: attachment.mimeType,
        fileSize: attachment.fileSize,
      }
    }
  } catch (error) {
    console.error("첨부파일 정보 조회 실패:", error)
    return { success: false, error: "첨부파일 정보 조회에 실패했습니다." }
  }
}
/**
 * Get vendor details by ID
 */
export const getVendorById = cache(async (vendorId: number) => {
  try {
    const [vendorData] = await db
      .select({
        id: vendors.id,
        name: vendors.vendorName,
        code: vendors.vendorCode,
        taxId: vendors.taxId,
        email: vendors.email,
        phone: vendors.phone,
        website: vendors.website,
        address: vendors.address,
        country: vendors.country,
        status: vendors.status,
        description: vendors.items, // Using items field as description for now
        vendorTypeId: vendors.vendorTypeId,
        representativeName: vendors.representativeName,
        representativeBirth: vendors.representativeBirth,
        representativeEmail: vendors.representativeEmail,
        representativePhone: vendors.representativePhone,
        corporateRegistrationNumber: vendors.corporateRegistrationNumber,
        creditAgency: vendors.creditAgency,
        creditRating: vendors.creditRating,
        cashFlowRating: vendors.cashFlowRating,
        businessSize: vendors.businessSize,
        createdAt: vendors.createdAt,
        updatedAt: vendors.updatedAt,
      })
      .from(vendors)
      .where(eq(vendors.id, vendorId))
      .limit(1)

    if (!vendorData) {
      throw new Error(`Vendor with ID ${vendorId} not found`)
    }

    return vendorData
  } catch (error) {
    console.error("Error fetching vendor:", error)
    throw new Error("Failed to fetch vendor details")
  }
})

/**
 * Get vendor items by vendor ID with caching
 */
export async function getVendorItemsByVendorId(vendorId: number) {
  return unstable_cache(
    async () => {
      try {
        // Join vendorPossibleItems with items table to get complete item information
        const vendorItems = await db
          .select({
            id: vendorPossibleItems.id,
            vendorId: vendorPossibleItems.vendorId,
            itemCode: vendorPossibleItems.itemCode,
            itemName: items.itemName,
            description: items.description,
            createdAt: vendorPossibleItems.createdAt,
            updatedAt: vendorPossibleItems.updatedAt,
          })
          .from(vendorPossibleItems)
          .leftJoin(
            items,
            eq(vendorPossibleItems.itemCode, items.itemCode)
          )
          .where(eq(vendorPossibleItems.vendorId, vendorId))
          .orderBy(vendorPossibleItems.createdAt)

        return vendorItems
      } catch (error) {
        console.error("Error fetching vendor items:", error)
        throw new Error("Failed to fetch vendor items")
      }
    },
    // Cache key
    [`vendor-items-${vendorId}`],
    {
      revalidate: 3600, // Cache for 1 hour
      tags: [`vendor-items-${vendorId}`, "vendor-items"],
    }
  )()
}

/**
 * Get all items for a vendor (alternative function name for clarity)
 */
export const getVendorPossibleItems = cache(async (vendorId: number) => {
  return getVendorItemsByVendorId(vendorId)
})

/**
 * Get vendor contacts by vendor ID
 * This function assumes you have a vendorContacts table
 */
export const getVendorContacts = cache(async (vendorId: number) => {
  try {
    // Note: This assumes you have a vendorContacts table
    // If you don't have this table yet, you can return an empty array
    // or implement based on your actual contacts storage structure
    
    // For now, returning empty array since vendorContacts table wasn't provided
    return []
    
    /* 
    // Uncomment and modify when you have vendorContacts table:
    const contacts = await db
      .select({
        id: vendorContacts.id,
        contactName: vendorContacts.name,
        contactEmail: vendorContacts.email,
        contactPhone: vendorContacts.phone,
        contactPosition: vendorContacts.position,
        isPrimary: vendorContacts.isPrimary,
        isActive: vendorContacts.isActive,
        createdAt: vendorContacts.createdAt,
        updatedAt: vendorContacts.updatedAt,
      })
      .from(vendorContacts)
      .where(
        and(
          eq(vendorContacts.vendorId, vendorId),
          eq(vendorContacts.isActive, true)
        )
      )

    return contacts
    */
  } catch (error) {
    console.error("Error fetching vendor contacts:", error)
    return []
  }
})

/**
 * Add an item to a vendor
 */
export async function addVendorItem(vendorId: number, itemCode: string) {
  try {
    // Check if the item exists
    const [item] = await db
      .select()
      .from(items)
      .where(eq(items.itemCode, itemCode))
      .limit(1)

    if (!item) {
      throw new Error(`Item with code ${itemCode} not found`)
    }

    // Check if the vendor-item relationship already exists
    const [existingRelation] = await db
      .select()
      .from(vendorPossibleItems)
      .where(
        eq(vendorPossibleItems.vendorId, vendorId) &&
        eq(vendorPossibleItems.itemCode, itemCode)
      )
      .limit(1)

    if (existingRelation) {
      throw new Error("This item is already associated with the vendor")
    }

    // Add the item to the vendor
    const [newVendorItem] = await db
      .insert(vendorPossibleItems)
      .values({
        vendorId,
        itemCode,
      })
      .returning()

    // Revalidate cache
    revalidateTag(`vendor-items-${vendorId}`)
    revalidateTag("vendor-items")

    return newVendorItem
  } catch (error) {
    console.error("Error adding vendor item:", error)
    throw new Error("Failed to add item to vendor")
  }
}

/**
 * Remove an item from a vendor
 */
export async function removeVendorItem(vendorId: number, itemCode: string) {
  try {
    await db
      .delete(vendorPossibleItems)
      .where(
        eq(vendorPossibleItems.vendorId, vendorId) &&
        eq(vendorPossibleItems.itemCode, itemCode)
      )

    // Revalidate cache
    revalidateTag(`vendor-items-${vendorId}`)
    revalidateTag("vendor-items")

    return { success: true }
  } catch (error) {
    console.error("Error removing vendor item:", error)
    throw new Error("Failed to remove item from vendor")
  }
}

/**
 * Get all available items (for adding to vendors)
 */
export const getAllItems = cache(async () => {
  try {
    const allItems = await db
      .select({
        id: items.id,
        itemCode: items.itemCode,
        itemName: items.itemName,
        description: items.description,
        createdAt: items.createdAt,
        updatedAt: items.updatedAt,
      })
      .from(items)
      .orderBy(items.itemName)

    return allItems
  } catch (error) {
    console.error("Error fetching all items:", error)
    throw new Error("Failed to fetch items")
  }
})

/**
 * Create vendor investigation attachment
 */
export async function createVendorInvestigationAttachmentAction(input: {
  investigationId: number;
  file: File;
  userId?: string;
}) {
  unstable_noStore();

  try {
    console.log(`📎 실사 첨부파일 생성 시작: ${input.file.name}`);

    // 1. saveDRMFile을 사용하여 파일 저장
    const saveResult = await saveDRMFile(
      input.file,
      decryptWithServerAction,
      `vendor-investigation/${input.investigationId}`,
      input.userId
    );

    if (!saveResult.success) {
      throw new Error(`파일 저장 실패: ${input.file.name} - ${saveResult.error}`);
    }

    console.log(`✅ 파일 저장 완료: ${input.file.name} -> ${saveResult.fileName}`);

    // 2. DB에 첨부파일 레코드 생성
    const [insertedAttachment] = await db
      .insert(vendorInvestigationAttachments)
      .values({
        investigationId: input.investigationId,
        fileName: saveResult.fileName!,
        originalFileName: input.file.name,
        filePath: saveResult.publicPath!,
        fileSize: input.file.size,
        mimeType: input.file.type || 'application/octet-stream',
        attachmentType: 'DOCUMENT', // 또는 파일 타입에 따라 결정
        createdAt: new Date(),
        updatedAt: new Date(),
      })
      .returning();

    console.log(`✅ 첨부파일 DB 레코드 생성 완료: ID ${insertedAttachment.id}`);

    // 3. 캐시 무효화
    revalidateTag(`vendor-investigation-${input.investigationId}`);
    revalidateTag("vendor-investigations");

    return {
      success: true,
      attachment: insertedAttachment,
    };
  } catch (error) {
    console.error(`❌ 실사 첨부파일 생성 실패: ${input.file.name}`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "알 수 없는 오류",
    };
  }
}

// 보완-재실사 요청 액션
export async function requestSupplementReinspectionAction({
  investigationId,
  siteVisitData
}: {
  investigationId: number;
  siteVisitData: {
    inspectionDuration?: number;
    requestedStartDate?: Date;
    requestedEndDate?: Date;
    shiAttendees?: any;
    vendorRequests?: any;
    additionalRequests?: string;
  };
}) {
  try {
    // 1. 실사 상태를 SUPPLEMENT_REQUIRED로 변경
    await db
      .update(vendorInvestigations)
      .set({
        investigationStatus: "SUPPLEMENT_REQUIRED",
        updatedAt: new Date(),
      })
      .where(eq(vendorInvestigations.id, investigationId));

    // 2. 새로운 방문실사 요청 생성
    const [newSiteVisitRequest] = await db
      .insert(siteVisitRequests)
      .values({
        investigationId: investigationId,
        inspectionDuration: siteVisitData.inspectionDuration,
        requestedStartDate: siteVisitData.requestedStartDate,
        requestedEndDate: siteVisitData.requestedEndDate,
        shiAttendees: siteVisitData.shiAttendees || {},
        vendorRequests: siteVisitData.vendorRequests || {},
        additionalRequests: siteVisitData.additionalRequests,
        status: "REQUESTED",
      })
      .returning();

    // 3. 캐시 무효화
    revalidateTag("vendor-investigations");
    revalidateTag("site-visit-requests");

    return { success: true, siteVisitRequestId: newSiteVisitRequest.id };
  } catch (error) {
    console.error("보완-재실사 요청 실패:", error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "알 수 없는 오류" 
    };
  }
}

// 보완-서류제출 요청 액션
export async function requestSupplementDocumentAction({
  investigationId,
  documentRequests
}: {
  investigationId: number;
  documentRequests: {
    requiredDocuments: string[];
    additionalRequests?: string;
  };
}) {
  try {
    // 1. 실사 상태를 SUPPLEMENT_REQUIRED로 변경
    await db
      .update(vendorInvestigations)
      .set({
        investigationStatus: "SUPPLEMENT_REQUIRED",
        updatedAt: new Date(),
      })
      .where(eq(vendorInvestigations.id, investigationId));

    // 2. 실사, 협력업체, 발송자 정보 조회
    const investigationResult = await db
      .select()
      .from(vendorInvestigations)
      .where(eq(vendorInvestigations.id, investigationId))
      .limit(1);
    
    const investigation = investigationResult[0];
    if (!investigation) {
      throw new Error('실사 정보를 찾을 수 없습니다.');
    }

    const vendorResult = await db
      .select()
      .from(vendors)
      .where(eq(vendors.id, investigation.vendorId))
      .limit(1);
    
    const vendor = vendorResult[0];
    if (!vendor) {
      throw new Error('협력업체 정보를 찾을 수 없습니다.');
    }

    const senderResult = await db
      .select()
      .from(users)
      .where(eq(users.id, investigation.requesterId!))
      .limit(1);
    
    const sender = senderResult[0];
    if (!sender) {
      throw new Error('발송자 정보를 찾을 수 없습니다.');
    }

    // 마감일 계산 (발송일 + 7일 또는 실사 예정일 중 먼저 도래하는 날)
    const deadlineDate = (() => {
      const deadlineFromToday = addDays(new Date(), 7);
      if (investigation.forecastedAt) {
        const forecastedDate = new Date(investigation.forecastedAt);
        return forecastedDate < deadlineFromToday ? forecastedDate : deadlineFromToday;
      }
      return deadlineFromToday;
    })();

    // 메일 제목
    const subject = `[SHI Audit] 보완 서류제출 요청 _ ${vendor.vendorName}`;

    // 메일 컨텍스트
    const context = {
      // 기본 정보
      vendorName: vendor.vendorName,
      vendorEmail: vendor.email || '',
      requesterName: sender.name,
      requesterTitle: 'Procurement Manager',
      requesterEmail: sender.email,

      // 보완 요청 서류
      requiredDocuments: documentRequests.requiredDocuments || [],

      // 추가 요청사항
      additionalRequests: documentRequests.additionalRequests || null,

      // 마감일
      deadlineDate: format(deadlineDate, 'yyyy.MM.dd'),

      // 포털 URL
      portalUrl: `${process.env.NEXT_PUBLIC_BASE_URL}/ko/partners/site-visit`,

      // 현재 연도
      currentYear: new Date().getFullYear()
    };

    // 메일 발송 (벤더 이메일로 직접 발송)
    try {
      await sendEmail({
        to: vendor.email || '',
        cc: sender.email,
        subject,
        template: 'supplement-document-request' as string,
        context,
      });

      console.log('보완 서류제출 요청 메일 발송 완료:', {
        to: vendor.email,
        subject,
        vendorName: vendor.vendorName
      });
    } catch (emailError) {
      console.error('보완 서류제출 요청 메일 발송 실패:', emailError);
    }

    // 3. 캐시 무효화
    revalidateTag("vendor-investigations");
    revalidateTag("site-visit-requests");

    return { success: true };
  } catch (error) {
    console.error("보완-서류제출 요청 실패:", error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "알 수 없는 오류" 
    };
  }
}

// 보완 서류 제출 완료 액션 (벤더가 서류 제출 완료)
export async function completeSupplementDocumentAction({
  investigationId,
  siteVisitRequestId,
  submittedBy
}: {
  investigationId: number;
  siteVisitRequestId: number;
  submittedBy: number;
}) {
  try {
    // 1. 방문실사 요청 상태를 COMPLETED로 변경
    await db
      .update(siteVisitRequests)
      .set({
        status: "COMPLETED",
        sentAt: new Date(),
        updatedAt: new Date(),
      })
      .where(eq(siteVisitRequests.id, siteVisitRequestId));

    // 2. 실사 상태를 IN_PROGRESS로 변경 (재검토 대기)
    await db
      .update(vendorInvestigations)
      .set({
        investigationStatus: "IN_PROGRESS",
        updatedAt: new Date(),
      })
      .where(eq(vendorInvestigations.id, investigationId));

    // 3. 캐시 무효화
    revalidateTag("vendor-investigations");
    revalidateTag("site-visit-requests");

    return { success: true };
  } catch (error) {
    console.error("보완 서류 제출 완료 처리 실패:", error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "알 수 없는 오류" 
    };
  }
}

// 보완 재실사 완료 액션 (재실사 완료 후)
export async function completeSupplementReinspectionAction({
  investigationId,
  siteVisitRequestId,
  evaluationResult,
  evaluationScore,
  investigationNotes
}: {
  investigationId: number;
  siteVisitRequestId: number;
  evaluationResult: "APPROVED" | "SUPPLEMENT" | "REJECTED";
  evaluationScore?: number;
  investigationNotes?: string;
}) {
  try {
    // 1. 방문실사 요청 상태를 COMPLETED로 변경
    await db
      .update(siteVisitRequests)
      .set({
        status: "COMPLETED",
        sentAt: new Date(),
        updatedAt: new Date(),
      })
      .where(eq(siteVisitRequests.id, siteVisitRequestId));

    // 2. 실사 상태 및 평가 결과 업데이트
    const updateData: any = {
      investigationStatus: evaluationResult === "APPROVED" ? "COMPLETED" : "SUPPLEMENT_REQUIRED",
      evaluationResult: evaluationResult,
      updatedAt: new Date(),
    };

    if (evaluationScore !== undefined) {
      updateData.evaluationScore = evaluationScore;
    }
    if (investigationNotes) {
      updateData.investigationNotes = investigationNotes;
    }
    if (evaluationResult === "COMPLETED") {
      updateData.completedAt = new Date();
    }

    await db
      .update(vendorInvestigations)
      .set(updateData)
      .where(eq(vendorInvestigations.id, investigationId));

    // 3. 캐시 무효화
    revalidateTag("vendor-investigations");
    revalidateTag("site-visit-requests");

    return { success: true };
  } catch (error) {
    console.error("보완 재실사 완료 처리 실패:", error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : "알 수 없는 오류" 
    };
  }
}

// 실사 보완요청 메일 발송 액션
export async function requestInvestigationSupplementAction({
  investigationId,
  vendorId,
  comment,
}: {
  investigationId: number;
  vendorId: number;
  comment: string;
}) {
  unstable_noStore();
  try {
    const headersList = await import("next/headers").then(m => m.headers());
    const host = headersList.get('host') || 'localhost:3000';

    // 실사/벤더 정보 조회
    const investigation = await db
      .select({
        id: vendorInvestigations.id,
        pqSubmissionId: vendorInvestigations.pqSubmissionId,
        investigationAddress: vendorInvestigations.investigationAddress,
      })
      .from(vendorInvestigations)
      .where(eq(vendorInvestigations.id, investigationId))
      .then(rows => rows[0]);

    const vendor = await db
      .select({ email: vendors.email, vendorName: vendors.vendorName })
      .from(vendors)
      .where(eq(vendors.id, vendorId))
      .then(rows => rows[0]);

    if (!vendor?.email) {
      return { success: false, error: "벤더 이메일 정보가 없습니다." };
    }

    // PQ 번호 조회
    let pqNumber = "N/A";
    if (investigation?.pqSubmissionId) {
      const pqRow = await db
        .select({ pqNumber: vendorPQSubmissions.pqNumber })
        .from(vendorPQSubmissions)
        .where(eq(vendorPQSubmissions.id, investigation.pqSubmissionId))
        .then(rows => rows[0]);
      if (pqRow) pqNumber = pqRow.pqNumber;
    }

    // 메일 발송
    const portalUrl = process.env.NEXTAUTH_URL || `http://${host}`;
    const reviewUrl = `${portalUrl}/evcp/vendor-investigation`;

    await sendEmail({
      to: vendor.email,
      subject: `[eVCP] 실사 보완요청 - ${vendor.vendorName}`,
      template: "pq-investigation-supplement-request",
      context: {
        vendorName: vendor.vendorName,
        investigationNumber: pqNumber,
        supplementComment: comment,
        requestedAt: new Date().toLocaleString('ko-KR'),
        reviewUrl: reviewUrl,
        year: new Date().getFullYear(),
      }
    });

    // 실사 상태를 SUPPLEMENT_REQUIRED로 변경 (이미 되어있을 수 있음)
    await db
      .update(vendorInvestigations)
      .set({
        investigationStatus: "SUPPLEMENT_REQUIRED",
        updatedAt: new Date(),
      })
      .where(eq(vendorInvestigations.id, investigationId));

    revalidateTag("vendor-investigations");
    revalidateTag("pq-submissions");

    return { success: true };
  } catch (error) {
    console.error("실사 보완요청 메일 발송 오류:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "알 수 없는 오류",
    };
  }
}

// 보완 서류제출 응답 제출 액션
export async function submitSupplementDocumentResponseAction({
  investigationId,
  responseData
}: {
  investigationId: number
  responseData: {
    responseText: string
    attachments: Array<{
      fileName: string
      url: string
      size?: number
    }>
  }
}) {
  try {
    // 1. 실사 상태를 SUPPLEMENT_REQUIRED로 변경
    await db
      .update(vendorInvestigations)
      .set({
        investigationStatus: "SUPPLEMENT_REQUIRED",
        investigationNotes: responseData.responseText,
        updatedAt: new Date(),
      })
      .where(eq(vendorInvestigations.id, investigationId));

    // 2. 첨부 파일 저장
    if (responseData.attachments.length > 0) {
      const attachmentData = responseData.attachments.map(attachment => ({
        investigationId,
        fileName: attachment.fileName,
        filePath: attachment.url,
        fileSize: attachment.size || 0,
        uploadedAt: new Date(),
      }));

      await db.insert(vendorInvestigationAttachments).values(attachmentData);
    }

    // 3. 캐시 무효화
    revalidateTag("vendor-investigations");
    revalidateTag("vendor-investigation-attachments");

    return { success: true };
  } catch (error) {
    console.error("보완 서류제출 응답 처리 실패:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "알 수 없는 오류"
    };
  }
}

// QM 담당자 변경 서버 액션
export async function updateQMManagerAction({
  investigationId,
  qmManagerId,
}: {
  investigationId: number;
  qmManagerId: number;
}) {
  try {
    // 1. 실사 정보 조회 (상태 확인)
    const investigation = await db
      .select({
        investigationStatus: vendorInvestigations.investigationStatus,
        currentQmManagerId: vendorInvestigations.qmManagerId,
      })
      .from(vendorInvestigations)
      .where(eq(vendorInvestigations.id, investigationId))
      .limit(1);

    if (!investigation || investigation.length === 0) {
      return {
        success: false,
        error: "실사를 찾을 수 없습니다."
      };
    }

    const currentInvestigation = investigation[0];

    // 2. 상태 검증 (계획 상태만 변경 가능)
    if (currentInvestigation.investigationStatus !== "PLANNED") {
      return {
        success: false,
        error: "계획 상태인 실사만 QM 담당자를 변경할 수 있습니다."
      };
    }

    // 3. QM 담당자 정보 조회
    const qmManager = await db
      .select({
        id: users.id,
        name: users.name,
        email: users.email,
      })
      .from(users)
      .where(eq(users.id, qmManagerId))
      .limit(1);

    if (!qmManager || qmManager.length === 0) {
      return {
        success: false,
        error: "존재하지 않는 QM 담당자입니다."
      };
    }

    const qmUser = qmManager[0];

    // 4. QM 담당자 업데이트
    await db
      .update(vendorInvestigations)
      .set({
        qmManagerId: qmManagerId,
        updatedAt: new Date(),
      })
      .where(eq(vendorInvestigations.id, investigationId));

    // 5. 캐시 무효화
    revalidateTag("vendor-investigations");

    return {
      success: true,
      message: "QM 담당자가 성공적으로 변경되었습니다."
    };

  } catch (error) {
    console.error("QM 담당자 변경 오류:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "QM 담당자 변경 중 오류가 발생했습니다."
    };
  }
}