summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/dolce-upload-service.ts
blob: 41b9c2fa78dfa8b2beed275a5ee7938c1b13f201 (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
// lib/vendor-document-list/dolce-upload-service.ts
import db from "@/db/db"
import { documents, revisions, documentAttachments, contracts, projects, vendors, issueStages } from "@/db/schema"
import { eq, and, inArray, min } from "drizzle-orm"
import { v4 as uuidv4 } from "uuid"
import * as crypto from "crypto"
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"

export interface DOLCEUploadResult {
  success: boolean
  uploadedDocuments: number
  uploadedFiles: number
  errors?: string[]
  results?: {
    documentResults?: any[]
    fileResults?: any[]
    mappingResults?: any[]
  }
}

interface ResultData {
  FileId: string;
  UploadId: string;
  FileSeq: number;
  FileName: string;
  FileRelativePath: string;
  FileSize: number;
  FileCreateDT: string; // ISO string format
  FileWriteDT: string; // ISO string format
  OwnerUserId: string;
}


interface FileReaderConfig {
  baseDir: string;
  isProduction: boolean;
}

interface DOLCEDocument {
  Mode: "ADD" | "MOD"
  Status: string
  RegisterId: number
  ProjectNo: string
  Discipline: string
  DrawingKind: string
  DrawingNo: string
  DrawingName: string
  RegisterGroupId: number
  RegisterSerialNo: number
  RegisterKind: string
  DrawingRevNo: string
  Category: string
  Receiver: string | null
  Manager: string
  RegisterDesc: string
  UploadId?: string
  RegCompanyCode: string
}

interface RevisionAttachment {
  id: number
  uploadId: string | null
  fileId: string | null
  fileName: string
  filePath: string
  fileType: string | null
  fileSize: number | null
  createdAt: Date
}

interface RevisionWithAttachments {
  id: number
  registerId: string | number | null
  revision: string
  revisionStatus: string | null
  uploaderId: string | number | null
  uploaderName: string | null
  submittedDate: string | null
  comment: string | null
  usage: string | null
  usageType: string | null
  externalUploadId: string | null
  externalRegisterId: number
  externalSentAt: string | null
  serialNo: number | null
  issueStageId: number
  stageName: string | null
  documentId: number
  documentNo: string
  documentName: string
  drawingKind: string | null
  drawingMoveGbn: string | null
  discipline: string | null
  registerGroupId: number | null
  category?: string | null
  cGbn: string | null
  dGbn: string | null
  degreeGbn: string | null
  deptGbn: string | null
  jGbn: string | null
  sGbn: string | null
  manager: string | null
  managerENM: string | null
  managerNo: string | null
  shiDrawingNo: string | null
  externalDocumentId: string | null
  externalSystemType: string | null
  externalSyncedAt: Date | null
  attachments: RevisionAttachment[]
}

interface DOLCEFileMapping {
  CGbn?: string | null
  Category?: string | null
  CheckBox: string
  DGbn?: string | null
  DegreeGbn?: string | null
  DeptGbn?: string | null
  Discipline: string
  DrawingKind: string
  DrawingMoveGbn: string
  DrawingName: string
  DrawingNo: string
  DrawingUsage: string
  FileNm: string
  JGbn?: string | null
  Manager: string
  MappingYN: string
  NewOrNot: string
  ProjectNo: string
  RegisterGroup: number
  RegisterGroupId: number
  RegisterKindCode: string
  RegisterSerialNo: number
  RevNo?: string | null
  SGbn?: string | null
  UploadId: string
}

function getFileReaderConfig(): FileReaderConfig {
  const isProduction = process.env.NODE_ENV === "production";

  if (isProduction) {
    return {
      baseDir: process.env.NAS_PATH || "/evcp_nas", // NAS 기본 경로
      isProduction: true,
    };
  } else {
    return {
      baseDir: process.cwd(), // 개발환경 현재 디렉토리
      isProduction: false,
    };
  }
}



class DOLCEUploadService {
  private readonly BASE_URL = process.env.DOLCE_API_URL || 'http://60.100.99.217:1111'
  private readonly UPLOAD_SERVICE_URL = process.env.DOLCE_UPLOAD_URL || 'http://60.100.99.217:1111/PWPUploadService.ashx'

  /**
   * 메인 업로드 함수: 변경된 문서와 파일을 DOLCE로 업로드
   */
  async uploadToDoLCE(
    projectId: number,
    revisionIds: number[],
    userId: string
  ): Promise<DOLCEUploadResult> {
    try {
      console.log(`Starting DOLCE upload for contract ${projectId}, revisions: ${revisionIds.join(', ')}`)

      // 1. 사용자 정보 조회 (DOLCE API에 필요한 정보)
      const userInfo = await this.getUserInfo(userId)
      if (!userInfo) {
        throw new Error(`User info not found for ID: ${userId}`)
      }

      // 2. 계약 정보 조회 (프로젝트 코드, 벤더 코드 등)
      const contractInfo = await this.getContractInfo(projectId)
      if (!contractInfo) {
        throw new Error(`Contract info not found for ID: ${projectId}`)
      }

      // 3. 업로드할 리비전 정보 조회
      const revisionsToUpload = await this.getRevisionsForUpload(revisionIds)
      if (revisionsToUpload.length === 0) {
        return {
          success: true,
          uploadedDocuments: 0,
          uploadedFiles: 0
        }
      }

      let uploadedDocuments = 0
      const uploadedFiles = 0
      const errors: string[] = []
      const results: any = {
        documentResults: [],
        fileResults: [],
        mappingResults: []
      }

      // 4. 각 리비전별로 처리
      for (const revision of revisionsToUpload) {
        try {
          console.log(`Processing revision ${revision.revision} for document ${revision.documentNo}`)

          // 4-1. UploadId 미리 생성 (파일이 있는 경우에만)
          let uploadId: string | undefined
          if (revision.attachments && revision.attachments.length > 0) {
            uploadId = uuidv4() // 문서 업로드 시 사용할 UploadId 미리 생성
            console.log(`Generated UploadId for document upload: ${uploadId}`)
          }

          // 4-2. 문서 정보 업로드 (UploadId 포함)
          const dolceDoc = this.transformToDoLCEDocument(
            revision,
            contractInfo,
            uploadId, // 미리 생성된 UploadId 사용
            contractInfo.vendorCode,
          )

          const docResult = await this.uploadDocument(
            [dolceDoc], 
            userInfo.userId,
            userInfo.userName,
            userInfo.vendorCode,
            userInfo.userEmail
          )
          if (!docResult.success) {
            errors.push(`Document upload failed for ${revision.documentNo}: ${docResult.error}`)
            continue // 문서 업로드 실패 시 다음 리비전으로 넘어감
          }

          uploadedDocuments++
          results.documentResults.push(docResult)
          console.log(`✅ Document uploaded successfully: ${revision.documentNo}`)

          // 4-3. 파일 업로드 (이미 생성된 UploadId 사용)
          if (uploadId && revision.attachments && revision.attachments.length > 0) {
            try {
              // 파일 업로드 시 이미 생성된 UploadId 사용
              await this.uploadFiles(
                revision.attachments,
                userId,
                uploadId // 이미 생성된 UploadId 전달
              )

            } catch (fileError) {
              errors.push(`File upload failed for ${revision.documentNo}: ${fileError instanceof Error ? fileError.message : 'Unknown error'}`)
              console.error(`❌ File upload failed for ${revision.documentNo}:`, fileError)
            }
          }

          // 4-4. 성공한 리비전의 상태 업데이트
          await this.updateRevisionStatus(revision.id, 'SUBMITTED', uploadId)

        } catch (error) {
          const errorMessage = `Failed to process revision ${revision.revision}: ${error instanceof Error ? error.message : 'Unknown error'}`
          errors.push(errorMessage)
          console.error(errorMessage, error)
        }
      }

      return {
        success: errors.length === 0,
        uploadedDocuments,
        uploadedFiles,
        errors: errors.length > 0 ? errors : undefined,
        results
      }

    } catch (error) {
      console.error('DOLCE upload failed:', error)
      throw error
    }
  }
  /**
   * 계약 정보 조회
   */
  private async getContractInfo(projectId: number): Promise<{
    projectCode: string;
    vendorCode: string;
  } | null> {

    const session = await getServerSession(authOptions)
    if (!session?.user?.companyId) {
      throw new Error("인증이 필요합니다.")
    }


    const [result] = await db
      .select({
        projectCode: projects.code,
        vendorCode: vendors.vendorCode
      })
      .from(contracts)
      .innerJoin(projects, eq(contracts.projectId, projects.id))
      .innerJoin(vendors, eq(contracts.vendorId, vendors.id))
      .where(and(eq(contracts.projectId, projectId), eq(contracts.vendorId, Number(session.user.companyId))))
      .limit(1)

    return result?.projectCode && result?.vendorCode
      ? { projectCode: result.projectCode, vendorCode: result.vendorCode }
      : null
  }

  /**
   * 사용자 정보 조회 (DOLCE 업로드에 필요한 정보)
   */
  private async getUserInfo(userId: string): Promise<{
    userId: string;
    userName: string;
    userEmail: string;
    vendorCode: string;
  } | null> {
    const { users, vendors } = await import("@/db/schema")
    
    // userId를 숫자로 변환하고 유효성 검증
    const userIdNum = Number(userId)
    if (isNaN(userIdNum) || userIdNum <= 0) {
      console.error(`Invalid userId: ${userId} (converted to NaN or invalid number)`)
      throw new Error(`Invalid user ID: ${userId}`)
    }
    
    const [result] = await db
      .select({
        userId: users.id,
        userName: users.name,
        userEmail: users.email,
        vendorCode: vendors.vendorCode
      })
      .from(users)
      .innerJoin(vendors, eq(users.companyId, vendors.id))
      .where(eq(users.id, userIdNum))
      .limit(1)

    if (!result) {
      return null
    }

    return {
      userId: String(result.userId),
      userName: result.userName,
      userEmail: result.userEmail,
      vendorCode: result.vendorCode || ""
    }
  }


  /**
   * 각 issueStageId별로 첫 번째 revision 정보를 조회
   */
  private async getFirstRevisionMap(issueStageIds: number[]): Promise<Map<number, string>> {
    const firstRevisions = await db
      .select({
        issueStageId: revisions.issueStageId,
        firstRevision: min(revisions.revision)
      })
      .from(revisions)
      .where(inArray(revisions.issueStageId, issueStageIds))
      .groupBy(revisions.issueStageId)

    const map = new Map<number, string>()
    firstRevisions.forEach(item => {
      if (item.firstRevision) {
        map.set(item.issueStageId, item.firstRevision)
      }
    })

    return map
  }

  /**
   * 업로드할 리비전 정보 조회 (문서 정보 및 첨부파일 포함)
   */
  private async getRevisionsForUpload(revisionIds: number[]): Promise<RevisionWithAttachments[]> {
    // revisions → issueStages → documents 순서로 join하여 정보 조회
    const revisionResults = await db
      .select({
        // revision 테이블 정보
        id: revisions.id,
        registerId: revisions.registerId,
        revision: revisions.revision, // revisionNo가 아니라 revision
        revisionStatus: revisions.revisionStatus,
        uploaderId: revisions.uploaderId,
        uploaderName: revisions.uploaderName,
        submittedDate: revisions.submittedDate,
        comment: revisions.comment,
        usage: revisions.usage,
        usageType: revisions.usageType,

        // ✅ DOLCE 연동 필드들 (새로 추가)
        externalUploadId: revisions.externalUploadId,
        externalRegisterId: revisions.id,
        externalSentAt: revisions.submittedDate,

        serialNo: revisions.serialNo,

        // issueStages 테이블 정보
        issueStageId: issueStages.id,
        stageName: issueStages.stageName,
        documentId: issueStages.documentId,

        // documents 테이블 정보 (DOLCE 업로드에 필요한 모든 필드)
        documentNo: documents.docNumber,
        documentName: documents.title,
        drawingKind: documents.drawingKind,
        drawingMoveGbn: documents.drawingMoveGbn,
        discipline: documents.discipline,
        registerGroupId: documents.registerGroupId,

        // DOLCE B4 전용 필드들
        cGbn: documents.cGbn,
        dGbn: documents.dGbn,
        degreeGbn: documents.degreeGbn,
        deptGbn: documents.deptGbn,
        jGbn: documents.jGbn,
        sGbn: documents.sGbn,

        // DOLCE 추가 정보
        manager: documents.manager,
        managerENM: documents.managerENM,
        managerNo: documents.managerNo,
        shiDrawingNo: documents.shiDrawingNo,

        // 외부 시스템 연동 정보
        externalDocumentId: documents.externalDocumentId,
        externalSystemType: documents.externalSystemType,
        externalSyncedAt: documents.externalSyncedAt
      })
      .from(revisions)
      .innerJoin(issueStages, eq(revisions.issueStageId, issueStages.id))
      .innerJoin(documents, eq(issueStages.documentId, documents.id))
      .where(inArray(revisions.id, revisionIds))

    // 각 리비전의 첨부파일 정보도 조회
    const revisionsWithAttachments: RevisionWithAttachments[] = []
    for (const revision of revisionResults) {
      const attachments = await db
        .select({
          id: documentAttachments.id,
          uploadId: documentAttachments.uploadId,
          fileId: documentAttachments.fileId,
          fileName: documentAttachments.fileName,
          filePath: documentAttachments.filePath,
          fileType: documentAttachments.fileType,
          fileSize: documentAttachments.fileSize,
          createdAt: documentAttachments.createdAt
        })
        .from(documentAttachments)
        .where(eq(documentAttachments.revisionId, revision.id))

      // serialNo를 숫자로 변환하여 RevisionWithAttachments 타입에 맞춤
      const convertedRevision: RevisionWithAttachments = {
        ...revision,
        serialNo: typeof revision.serialNo === 'string' ? Number(revision.serialNo) : revision.serialNo,
        attachments
      }
      
      revisionsWithAttachments.push(convertedRevision)
    }

    return revisionsWithAttachments
  }

  /**
   * 파일 업로드 (PWPUploadService.ashx) - 수정된 버전
   * @param attachments 업로드할 첨부파일 목록
   * @param userId 사용자 ID
   * @param uploadId 이미 생성된 UploadId (문서 업로드 시 생성됨)
   */
  private async uploadFiles(
    attachments: RevisionAttachment[],
    userId: string,
    uploadId: string // 이미 생성된 UploadId를 매개변수로 받음
  ): Promise<Array<{ uploadId: string, fileId: string, filePath: string }>> {
    const uploadResults: Array<{ uploadId: string, fileId: string, filePath: string }> = []
    const resultDataArray: ResultData[] = []

    for (let i = 0; i < attachments.length; i++) {
      const attachment = attachments[i]
      try {
        // FileId만 새로 생성 (UploadId는 이미 생성된 것 사용)
        const fileId = uuidv4()

        console.log(`Uploading file with predefined UploadId: ${uploadId}, FileId: ${fileId}`)

        // 파일 데이터 읽기
        const fileBuffer = await this.getFileBuffer(attachment.filePath)

        const uploadUrl = `${this.UPLOAD_SERVICE_URL}?UploadId=${uploadId}&FileId=${fileId}`

        const response = await fetch(uploadUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/octet-stream',
          },
          body: fileBuffer
        })

        if (!response.ok) {
          const errorText = await response.text()
          throw new Error(`File upload failed: HTTP ${response.status} - ${errorText}`)
        }

        const dolceFilePath = await response.text() // DOLCE에서 반환하는 파일 경로

        // 업로드 성공 후 documentAttachments 테이블 업데이트
        await db
          .update(documentAttachments)
          .set({
            uploadId: uploadId, // 이미 생성된 UploadId 사용
            fileId: fileId,
            uploadedBy: userId,
            dolceFilePath: dolceFilePath,
            uploadedAt: new Date(),
            updatedAt: new Date()
          })
          .where(eq(documentAttachments.id, attachment.id))

        uploadResults.push({
          uploadId,
          fileId,
          filePath: dolceFilePath
        })

        // ResultData 객체 생성 (PWPUploadResultService 호출용)
        const fileStats = await this.getFileStats(attachment.filePath) // 파일 통계 정보 조회
        const fileSize = fileBuffer.byteLength

        const resultData: ResultData = {
          FileId: fileId,
          UploadId: uploadId,
          FileSeq: i + 1, // 1부터 시작하는 시퀀스
          FileName: attachment.fileName,
          FileRelativePath: dolceFilePath,
          // FileSize: fileStats.size, // 사이즈 조회 결과 문제로, 파일 버퍼의 사이즈를 사용
          FileSize: fileSize,
          FileCreateDT: fileStats.birthtime.toISOString(),
          FileWriteDT: fileStats.mtime.toISOString(),
          OwnerUserId: userId
        }

        resultDataArray.push(resultData)

        console.log(`✅ File uploaded successfully: ${attachment.fileName} -> ${dolceFilePath}`)
        console.log(`✅ DB updated for attachment ID: ${attachment.id}`)

        // 🧪 DOLCE 업로드 확인 테스트
        try {
          const testResult = await this.testDOLCEFileDownload(fileId, userId, attachment.fileName)
          if (testResult.success) {
            console.log(`✅ DOLCE 업로드 확인 성공: ${attachment.fileName}`)
          } else {
            console.warn(`⚠️ DOLCE 업로드 확인 실패: ${attachment.fileName} - ${testResult.error}`)
          }
        } catch (testError) {
          console.warn(`⚠️ DOLCE 업로드 확인 중 오류: ${attachment.fileName}`, testError)
        }

      } catch (error) {
        console.error(`❌ File upload failed for ${attachment.fileName}:`, error)
        throw error
      }
    }

    // 모든 파일 업로드가 완료된 후 PWPUploadResultService 호출
    if (resultDataArray.length > 0) {
      try {
        await this.finalizeUploadResult(resultDataArray)
        console.log(`✅ Upload result finalized for UploadId: ${uploadId}`)
      } catch (error) {
        console.error(`❌ Failed to finalize upload result for UploadId: ${uploadId}`, error)
        // 파일 업로드는 성공했지만 결과 저장 실패 - 로그만 남기고 계속 진행
      }
    }

    return uploadResults
  }


  private async finalizeUploadResult(resultDataArray: ResultData[]): Promise<void> {
    const url = `${this.BASE_URL}/PWPUploadResultService.ashx?`

    try {
      const jsonData = JSON.stringify(resultDataArray)
      const dataBuffer = Buffer.from(jsonData, 'utf-8')

      console.log(`Calling PWPUploadResultService with ${resultDataArray.length} files`)
      console.log('ResultData:', JSON.stringify(resultDataArray, null, 2))

      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: dataBuffer
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`PWPUploadResultService failed: HTTP ${response.status} - ${errorText}`)
      }

      const result = await response.text()

      if (result !== 'Success') {
        console.log(result, "돌체 업로드 실패")
        throw new Error(`PWPUploadResultService returned unexpected result: ${result}`)
      }

      console.log('✅ PWPUploadResultService call successful')

    } catch (error) {
      console.error('❌ PWPUploadResultService call failed:', error)
      throw error
    }
  }

  // 파일 통계 정보 조회 헬퍼 메서드 (파일시스템에서 파일 정보를 가져옴)
  private async getFileStats(filePath: string): Promise<{ size: number, birthtime: Date, mtime: Date }> {
    try {
      // Node.js 환경이라면 fs.stat 사용
      const fs = await import('fs/promises')
      const stats = await fs.stat(filePath)

      return {
        size: stats.size,
        birthtime: stats.birthtime,
        mtime: stats.mtime
      }
    } catch {
      console.warn(`Could not get file stats for ${filePath}, using defaults`)
      // 파일 정보를 가져올 수 없는 경우 기본값 사용
      const now = new Date()
      return {
        size: 0,
        birthtime: now,
        mtime: now
      }
    }
  }

  /**
   * 문서 정보 업로드 (DetailDwgReceiptMgmtEdit)
   */
  private async uploadDocument(
    dwgList: DOLCEDocument[], 
    userId: string,
    userName: string,
    vendorCode: string,
    email: string
  ): Promise<{ success: boolean, error?: string, data?: any }> {
    try {
      const endpoint = `${this.BASE_URL}/Services/VDCSWebService.svc/DetailDwgReceiptMgmtEdit`

      // UserID를 숫자로 변환하고 유효성 검증
      const userIdNum = Number(userId)
      if (isNaN(userIdNum) || userIdNum <= 0) {
        throw new Error(`Invalid UserID for DOLCE API: ${userId} (must be a positive integer)`)
      }

      const requestBody = {
        DwgList: dwgList,
        UserID: userIdNum, // 정수형으로 변환
        UserNM: userName,
        VENDORCODE: vendorCode,
        EMAIL: email
      }

      console.log('Uploading documents to DOLCE:', JSON.stringify(requestBody, null, 2))

      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody)
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`HTTP ${response.status} - ${errorText}`)
      }

      const result = await response.json()

      return {
        success: true,
        data: result
      }

    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 파일 매핑 정보 업로드 (MatchBatchFileDwgEdit)
   */
  private async uploadFileMapping(mappingList: DOLCEFileMapping[], userId: string): Promise<{ success: boolean, error?: string, data?: any }> {
    try {
      const endpoint = `${this.BASE_URL}/Services/VDCSWebService.svc/MatchBatchFileDwgEdit`

      // UserID를 숫자로 변환하고 유효성 검증
      const userIdNum = Number(userId)
      if (isNaN(userIdNum) || userIdNum <= 0) {
        throw new Error(`Invalid UserID for DOLCE API: ${userId} (must be a positive integer)`)
      }

      const requestBody = {
        mappingSaveLists: mappingList,
        UserID: userIdNum // 정수형으로 변환
      }

      console.log('Uploading file mapping to DOLCE:', JSON.stringify(requestBody, null, 2))

      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody)
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`HTTP ${response.status} - ${errorText}`)
      }

      const result = await response.json()

      return {
        success: true,
        data: result
      }

    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 리비전 데이터를 DOLCE 문서 형태로 변환 (업데이트된 스키마 사용)
   */
  private transformToDoLCEDocument(
    revision: RevisionWithAttachments,
    contractInfo: { projectCode: string; vendorCode: string },
    uploadId?: string,
    vendorCode?: string,
  ): DOLCEDocument {
    // Mode 결정: registerId가 있으면 MOD, 없으면 ADD
    let mode: "ADD" | "MOD" = "ADD" // 기본값은 ADD

    if (revision.registerId) {
      mode = "MOD"
    } else {
      mode = "ADD"
    }

    // RegisterKind 결정: usage와 usageType에 따라 설정
    let registerKind = "APPR" // 기본값

    if (revision.usage && revision.usage !== 'DEFAULT') {
      switch (revision.usage) {

        case "APPROVAL":
          if (revision.drawingKind === "B3") {
            if (revision.usageType === "Full") {
              registerKind = "APPR"
            } else if (revision.usageType === "Partial") {
              registerKind = "APPR-P"
            } else {
              registerKind = "APPR" // 기본값
            }
          }
          break

        case "WORKING":
          if (revision.drawingKind === "B3") {
            if (revision.usageType === "Full") {
              registerKind = "WORK"
            } else if (revision.usageType === "Partial") {
              registerKind = "WORK-P"
            } else {
              registerKind = "WORK" // 기본값
            }
          }
          break

        case "The 1st":
          if (revision.drawingKind === "B5") {
            registerKind = "FMEA-1"
          }
          break

        case "The 2nd":
          if (revision.drawingKind === "B5") {
            registerKind = "FMEA-2"
          }
          break

        case "Pre":
          if (revision.drawingKind === "B3") {
            registerKind = "RECP"
          }
          break

        case "Working":
          if (revision.drawingKind === "B3") {
            registerKind = "RECW"
          }
          break

        case "Mark-Up":
          registerKind = "CMTM"
          break

        case "Comment":
          // 김혜빈 프로 요청사항 20250826
          // DrawingKind에 따라 분기
          if (revision.drawingKind === "B3") {
            registerKind = "CMTV" // B3(Vendor) Comment
          } else if (revision.drawingKind === "B4" && revision.drawingMoveGbn === "GTT Deliverable") {
            registerKind = "CMTQ" // B4(GTT) + GTT Deliverable
          } else {
            registerKind = "CMTV" // 기타 Comment (기본)
          }
          break

        default:
          console.warn(`Unknown usage type: ${revision.usage}, using default APPR`)
          registerKind = "APPR" // 기본값
          break
      }
    } else {
      console.warn(`No usage specified for revision ${revision.revision}, using default APPR`)
    }

    // Serial Number 계산 함수
    const getSerialNumber = (revisionValue: string): number => {
      if (!revisionValue) {
        return 1
      }

      // 먼저 숫자인지 확인
      const numericValue = parseInt(revisionValue)
      if (!isNaN(numericValue)) {
        return numericValue
      }

      // 문자인 경우 (a=1, b=2, c=3, ...)
      if (typeof revisionValue === 'string' && revisionValue.length === 1) {
        const charCode = revisionValue.toLowerCase().charCodeAt(0)
        if (charCode >= 97 && charCode <= 122) { // a-z
          return charCode - 96 // a=1, b=2, c=3, ...
        }
      }

      // 기본값
      return 1
    }

    console.log(`Transform to DOLCE: Mode=${mode}, RegisterKind=${registerKind}, Usage=${revision.usage}, UsageType=${revision.usageType}`)

    return {
      Mode: mode,
      // Status: revision.revisionStatus || "Standby",
      Status: "Standby",
      RegisterId: revision.registerId ? (typeof revision.registerId === 'string' ? parseInt(revision.registerId) : revision.registerId) : 0, // registerId가 없으면 0 (ADD 모드)
      ProjectNo: contractInfo.projectCode,
      Discipline: revision.discipline || "DL",
      DrawingKind: revision.drawingKind || "B3",
      DrawingNo: revision.documentNo,
      DrawingName: revision.documentName,
      RegisterGroupId: revision.registerGroupId || 0,
      RegisterSerialNo: revision.serialNo || getSerialNumber(revision.revision || "1"),
      RegisterKind: registerKind, // usage/usageType에 따라 동적 설정
      DrawingRevNo: revision.revision || "-",
      Category: revision.category || "TS",
      Receiver: null,
      Manager: revision.managerNo || "202206", // 담당자 번호 사용
      RegisterDesc: revision.comment || "System upload",
      UploadId: uploadId,
      RegCompanyCode: vendorCode || "A0005531" // 벤더 코드
    }
  }
  /**
   * 파일 매핑 데이터 변환
   */
  private transformToFileMapping(
    revision: RevisionWithAttachments,
    contractInfo: { projectCode: string; vendorCode: string },
    uploadId: string,
    fileName: string
  ): DOLCEFileMapping {
    return {
      CGbn: revision.cGbn,
      Category: revision.category,
      CheckBox: "0",
      DGbn: revision.dGbn,
      DegreeGbn: revision.degreeGbn,
      DeptGbn: revision.deptGbn,
      Discipline: revision.discipline || "DL",
      DrawingKind: revision.drawingKind || "B4",
      DrawingMoveGbn: revision.drawingMoveGbn || "도면입수",
      DrawingName: revision.documentName,
      DrawingNo: revision.documentNo,
      DrawingUsage: "입수용",
      FileNm: fileName,
      JGbn: revision.jGbn,
      Manager: revision.managerNo || "970043",
      MappingYN: "Y",
      NewOrNot: "N",
      ProjectNo: contractInfo.projectCode,
      RegisterGroup: 0,
      RegisterGroupId: revision.registerGroupId || 0,
      RegisterKindCode: "RECW",
      RegisterSerialNo: parseInt(revision.revision) || 1,
      RevNo: revision.revision,
      SGbn: revision.sGbn,
      UploadId: uploadId
    }
  }



  /**
   * 파일 버퍼 읽기 (실제 파일 시스템 기반) - 타입 에러 수정
   */
  private async getFileBuffer(filePath: string): Promise<ArrayBuffer> {
    try {
      console.log(`📂 파일 읽기 요청: ${filePath}`);

      if (filePath.startsWith('http')) {
        // ✅ URL인 경우 직접 다운로드 (기존과 동일)
        console.log(`🌐 HTTP URL에서 파일 다운로드: ${filePath}`);

        const response = await fetch(filePath);
        if (!response.ok) {
          throw new Error(`파일 다운로드 실패: ${response.status}`);
        }

        const arrayBuffer = await response.arrayBuffer();
        console.log(`✅ HTTP 다운로드 완료: ${arrayBuffer.byteLength} bytes`);

        return arrayBuffer;
      } else {
        // ✅ 로컬/NAS 파일 경로 처리 (환경별 분기)
        const fs = await import('fs');
        const path = await import('path');
        const config = getFileReaderConfig();

        let actualFilePath: string;

        // 경로 형태별 처리
        if (filePath.startsWith('/documents/')) {
          // ✅ DB에 저장된 경로 형태: "/documents/[uuid].ext"
          // 개발: public/documents/[uuid].ext
          // 프로덕션: /evcp_nas/documents/[uuid].ext
          if (config.isProduction) {
            // 프로덕션: NAS 경로에 직접 documents 추가
            actualFilePath = path.join(config.baseDir, filePath.substring(1)); // 앞의 '/' 제거
          } else {
            // 개발: public/documents/[uuid].ext
            actualFilePath = path.join(config.baseDir, 'public', filePath.substring(1)); // 앞의 '/' 제거
          }
          console.log(`📁 documents 경로 처리: ${filePath} → ${actualFilePath}`);
        }
        else if (filePath.startsWith('/api/files')) {

          actualFilePath = `${process.env.NEXT_PUBLIC_URL}${filePath}`


          const response = await fetch(actualFilePath);
          if (!response.ok) {
            throw new Error(`파일 다운로드 실패: ${response.status}`);
          }

          const arrayBuffer = await response.arrayBuffer();
          console.log(`✅ HTTP 다운로드 완료: ${arrayBuffer.byteLength} bytes`);

          return arrayBuffer;

        }

        else {
          // ✅ 상대 경로는 현재 디렉토리 기준
          actualFilePath = filePath;
          console.log(`📂 상대 경로 사용: ${actualFilePath}`);
        }

        console.log(`🔍 실제 파일 경로: ${actualFilePath}`);
        console.log(`🏠 환경: ${config.isProduction ? 'PRODUCTION (NAS)' : 'DEVELOPMENT (public)'}`);

        // 파일 존재 여부 확인
        if (!fs.existsSync(actualFilePath)) {
          console.error(`❌ 파일 없음: ${actualFilePath}`);
          throw new Error(`파일을 찾을 수 없습니다: ${actualFilePath}`);
        }

        // 파일 읽기
        const fileBuffer = fs.readFileSync(actualFilePath);
        console.log(`✅ 파일 읽기 성공: ${actualFilePath} (${fileBuffer.length} bytes)`);

        // ✅ Buffer를 ArrayBuffer로 정확히 변환
        const arrayBuffer = new ArrayBuffer(fileBuffer.length);
        const uint8Array = new Uint8Array(arrayBuffer);
        uint8Array.set(fileBuffer);

        return arrayBuffer;
      }
    } catch (error) {
      console.error(`❌ 파일 읽기 실패: ${filePath}`, error);
      throw error;
    }
  }

  /**
   * 리비전 상태 업데이트 (업데이트된 스키마 사용)
   */
  private async updateRevisionStatus(revisionId: number, status: string, uploadId?: string) {
    const updateData: any = {
      revisionStatus: status,
      updatedAt: new Date()
    }

    // 업로드 성공 시 관련 날짜 설정
    if (status === 'SUBMITTED') {
      updateData.submittedDate = new Date().toISOString().slice(0, 10)
      //   updateData.externalSentAt = new Date().toISOString().slice(0, 10)
    } else if (status === 'APPROVED') {
      updateData.approvedDate = new Date().toISOString().slice(0, 10)
    }

    // DOLCE 업로드 ID 저장
    if (uploadId) {
      updateData.externalUploadId = uploadId
    }

    await db
      .update(revisions)
      .set(updateData)
      .where(eq(revisions.id, revisionId))

    console.log(`✅ Updated revision ${revisionId} status to ${status}${uploadId ? ` with upload ID: ${uploadId}` : ''}`)
  }

  /**
   * 업로드 가능 여부 확인
   */
  isUploadEnabled(): boolean {
    const enabled = process.env.DOLCE_UPLOAD_ENABLED
    return enabled === 'true' || enabled === '1'
  }

  /**
   * DOLCE 업로드 확인 테스트 (업로드 후 파일이 DOLCE에 존재하는지 확인)
   */
  private async testDOLCEFileDownload(
    fileId: string,
    userId: string,
    fileName: string
  ): Promise<{ success: boolean; downloadUrl?: string; error?: string }> {
    try {
      // DES 암호화 (C# DESCryptoServiceProvider 호환)
      const DES_KEY = Buffer.from("4fkkdijg", "ascii")

      // 암호화 문자열 생성: FileId↔UserId↔FileName
      const encryptString = `${fileId}↔${userId}↔${fileName}`

      // DES 암호화 (createCipheriv 사용)
      const cipher = crypto.createCipheriv('des-ecb', DES_KEY, '')
      cipher.setAutoPadding(true)
      let encrypted = cipher.update(encryptString, 'utf8', 'base64')
      encrypted += cipher.final('base64')
      const encryptedKey = encrypted.replace(/\+/g, '|||')

      const downloadUrl = `${process.env.DOLCE_DOWNLOAD_URL}?key=${encryptedKey}` || `http://60.100.99.217:1111/Download.aspx?key=${encryptedKey}`

      console.log(`🧪 DOLCE 파일 다운로드 테스트:`)
      console.log(`   파일명: ${fileName}`)
      console.log(`   FileId: ${fileId}`)
      console.log(`   UserId: ${userId}`)
      console.log(`   암호화 키: ${encryptedKey}`)
      console.log(`   다운로드 URL: ${downloadUrl}`)

      const response = await fetch(downloadUrl, {
        method: 'GET',
        headers: {
          'User-Agent': 'DOLCE-Integration-Service'
        }
      })

      if (!response.ok) {
        console.error(`❌ DOLCE 파일 다운로드 테스트 실패: HTTP ${response.status}`)
        return {
          success: false,
          downloadUrl,
          error: `HTTP ${response.status}`
        }
      }

      const buffer = Buffer.from(await response.arrayBuffer())
      console.log(`✅ DOLCE 파일 다운로드 테스트 성공: ${fileName} (${buffer.length} bytes)`)

      return {
        success: true,
        downloadUrl
      }

    } catch (error) {
      console.error(`❌ DOLCE 파일 다운로드 테스트 실패: ${fileName}`, error)
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }
}

export const dolceUploadService = new DOLCEUploadService()

// 편의 함수
export async function uploadRevisionsToDOLCE(
  projectId: number,
  revisionIds: number[],
  userId: string
): Promise<DOLCEUploadResult> {
  return dolceUploadService.uploadToDoLCE(projectId, revisionIds, userId)
}