import { NextRequest, NextResponse } from 'next/server'; import fs from 'fs/promises'; import path from 'path'; import db from "@/db/db"; import { basicContractTemplates } from '@/db/schema'; import { eq } from 'drizzle-orm'; export async function POST(request: NextRequest) { try { const { templateId } = await request.json(); if (!templateId) { return NextResponse.json({ error: '템플릿 ID가 누락되었습니다.' }, { status: 400 }); } // 데이터베이스에서 템플릿 정보 가져오기 const template = await db.query.basicContractTemplates.findFirst({ where: eq(basicContractTemplates.id, templateId) }); if (!template) { return NextResponse.json({ error: '템플릿을 찾을 수 없습니다.' }, { status: 404 }); } if (!template.filePath) { return NextResponse.json({ error: '템플릿 파일 경로가 없습니다.' }, { status: 404 }); } // 환경에 따른 파일 경로 설정 let fullPath: string; if (process.env.NODE_ENV === 'production') { // production: NAS 경로 사용 const nasPath = process.env.NAS_PATH || "/evcp_nas"; // template.filePath가 /api/files/로 시작하는 경우 제거하고 basicContract로 시작하도록 정리 const cleanPath = template.filePath.startsWith('/api/files/') ? template.filePath.replace('/api/files/', '') : template.filePath.startsWith('/') ? template.filePath.slice(1) : template.filePath; fullPath = path.join(nasPath, cleanPath); } else { // development: public 폴더 사용 // template.filePath에서 앞의 슬래시를 제거 const cleanPath = template.filePath.startsWith('/') ? template.filePath.slice(1) : template.filePath; fullPath = path.join(process.cwd(), "public", cleanPath); } console.log(`📁 템플릿 파일 경로: ${fullPath} (환경: ${process.env.NODE_ENV})`); try { const fileBuffer = await fs.readFile(fullPath); // 파일을 Blob으로 반환 return new NextResponse(fileBuffer, { status: 200, headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'Content-Disposition': `attachment; filename="${encodeURIComponent(template.fileName || 'template.docx')}"`, }, }); } catch (fileError) { console.error('파일 읽기 오류:', fileError); console.error(`파일 경로: ${fullPath}`); console.error(`template.filePath: ${template.filePath}`); return NextResponse.json({ error: '템플릿 파일을 읽을 수 없습니다.', details: `파일 경로: ${fullPath}`, originalPath: template.filePath }, { status: 500 }); } } catch (error) { console.error('템플릿 가져오기 오류:', error); return NextResponse.json({ error: '서버 오류가 발생했습니다.' }, { status: 500 }); } }