summaryrefslogtreecommitdiff
path: root/app/api/attachment-delete/route.ts
blob: cfaba61c2b16aecb8a4c5c2e1e4cb4b38107d721 (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
// /api/attachment-delete/route.ts

import { NextRequest, NextResponse } from 'next/server'
import db from '@/db/db'
import { documentAttachments, changeLogs } from '@/db/schema'
import { eq, and } from 'drizzle-orm'
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';

export async function DELETE(request: NextRequest) {
  try {

    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json(
        { error: '인증이 필요합니다' },
        { status: 401 }
      );
    }

    const { attachmentId, revisionId } = await request.json()

    if (!attachmentId || !revisionId) {
      return NextResponse.json(
        { error: 'attachmentId and revisionId are required' },
        { status: 400 }
      )
    }

    // 1. 데이터베이스에서 첨부파일 정보 조회
    const attachment = await db
      .select()
      .from(documentAttachments)
      .where(
        and(
          eq(documentAttachments.id, attachmentId),
          eq(documentAttachments.revisionId, revisionId)
        )
      )
      .limit(1)

    if (!attachment || attachment.length === 0) {
      return NextResponse.json(
        { error: 'Attachment not found' },
        { status: 404 }
      )
    }

    const attachmentData = attachment[0]

    // 2. dolceFilePath 체크 - 있으면 삭제 불가
    if (attachmentData.dolceFilePath && attachmentData.dolceFilePath.trim() !== '') {
      return NextResponse.json(
        { error: 'Cannot delete processed file' },
        { status: 403 }
      )
    }

    // 3. 트랜잭션으로 첨부파일과 changeLogs 함께 삭제
    await db.transaction(async (tx) => {
      // 3-1. changeLogs에서 해당 attachment 관련 로그 삭제
      await tx
        .delete(changeLogs)
        .where(
          and(
            eq(changeLogs.entityType, 'attachment'),
            eq(changeLogs.entityId, attachmentId)
          )
        )

      // 3-2. 첨부파일 레코드 삭제
      await tx
        .delete(documentAttachments)
        .where(
          and(
            eq(documentAttachments.id, attachmentId),
            eq(documentAttachments.revisionId, revisionId)
          )
        )
    })

    return NextResponse.json({
      success: true,
      message: 'Attachment and related logs deleted successfully',
      deletedAttachmentId: attachmentId
    })

  } catch (error) {
    console.error('Attachment deletion error:', error)
    return NextResponse.json(
      { 
        error: 'Internal server error',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}