import { NextRequest, NextResponse } from 'next/server' import { authMiddleware } from '@/lib/auth-middleware' import { moveToPermStorage, generateUniqueFilename, deleteFile } from '@/lib/file-vault' import { z } from 'zod' // Confirm upload request validation const confirmSchema = z.object({ tempPath: z.string().min(1, 'Temporary path is required'), permanentFolder: z.string().optional().default('uploads'), filename: z.string().optional(), }) export async function POST(request: NextRequest) { try { // Check authentication const user = await authMiddleware(request) if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const body = await request.json() const { tempPath, permanentFolder, filename } = confirmSchema.parse(body) // Validate temp path format if (!tempPath.startsWith('temp/')) { return NextResponse.json({ error: 'Invalid temporary path' }, { status: 400 }) } // Generate permanent path const originalFilename = tempPath.split('/').pop() || 'file' const finalFilename = filename ? generateUniqueFilename(filename) : originalFilename const permanentPath = `${permanentFolder}/${finalFilename}` // Move file from temp to permanent storage await moveToPermStorage(tempPath, permanentPath) // TODO: Save file metadata to database // This would include: // - permanentPath // - originalFilename // - uploadedBy (user.id) // - uploadedAt // - fileSize // - mimeType return NextResponse.json({ success: true, data: { permanentPath, filename: finalFilename, folder: permanentFolder, confirmedBy: user.id, confirmedAt: new Date().toISOString(), }, }) } catch (error) { console.error('Upload confirmation error:', error) if (error instanceof z.ZodError) { return NextResponse.json( { error: 'Invalid request parameters', details: error.issues }, { status: 400 } ) } return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) } } // Delete temporary file (cleanup) export async function DELETE(request: NextRequest) { try { // Check authentication const user = await authMiddleware(request) if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const { searchParams } = new URL(request.url) const tempPath = searchParams.get('path') if (!tempPath) { return NextResponse.json({ error: 'Temporary path is required' }, { status: 400 }) } // Validate temp path format if (!tempPath.startsWith('temp/')) { return NextResponse.json({ error: 'Invalid temporary path' }, { status: 400 }) } // Delete temporary file await deleteFile(tempPath) return NextResponse.json({ success: true, message: 'Temporary file deleted successfully', }) } catch (error) { console.error('Temporary file deletion error:', error) return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) } }