import { NextRequest, NextResponse } from 'next/server' import { requireAuth } from '@/lib/auth' import { createUploadSession, generatePresignedUrl, validateFileType, validateFileSize } from '@/lib/upload' export async function POST(request: NextRequest) { try { const user = await requireAuth() const body = await request.json() const { fileName, fileSize, mimeType, chunkSize, metadata } = body // Validate required fields if (!fileName || !fileSize || !mimeType) { return NextResponse.json( { error: 'Missing required fields: fileName, fileSize, mimeType' }, { status: 400 } ) } // Validate file size (max 500MB) const maxSize = 500 * 1024 * 1024 // 500MB if (!validateFileSize(fileSize, maxSize)) { return NextResponse.json( { error: `File size exceeds maximum allowed size of ${maxSize / 1024 / 1024}MB` }, { status: 400 } ) } // Validate allowed file types const allowedTypes = [ 'audio/*', 'image/*', ] if (!validateFileType(mimeType, allowedTypes)) { return NextResponse.json( { error: 'File type not allowed' }, { status: 400 } ) } // Create upload session const uploadSession = await createUploadSession( user.id, fileName, fileSize, mimeType, chunkSize, metadata ) // Generate first chunk presigned URL const { url, key } = await generatePresignedUrl( `chunk-0-${fileName}`, mimeType ) return NextResponse.json( { uploadSession, presignedUrl: url, uploadKey: key, chunkSize: uploadSession.chunkSize, totalChunks: uploadSession.totalChunks, }, { status: 201 } ) } catch (error) { console.error('Upload init error:', error) if (error instanceof Error && error.message === 'Unauthorized') { return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ) } return NextResponse.json( { error: 'Failed to initialize upload' }, { status: 500 } ) } }