53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { auth } from '@/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await auth()
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
const userId = session.user.id
|
|
|
|
// 1. Find and delete labels that have no notes and belong to this user
|
|
// We only delete labels that are not part of a notebook (global labels)
|
|
const orphanedLabels = await prisma.label.findMany({
|
|
where: {
|
|
userId,
|
|
notebookId: null,
|
|
notes: { none: {} }
|
|
}
|
|
})
|
|
|
|
await prisma.label.deleteMany({
|
|
where: {
|
|
id: { in: orphanedLabels.map(l => l.id) }
|
|
}
|
|
})
|
|
|
|
// 2. Clean up NoteEmbeddings that don't have a corresponding Note (shouldn't happen with Cascade, but good for cleanup)
|
|
const orphanedEmbeddings = await prisma.noteEmbedding.findMany({
|
|
where: {
|
|
note: { userId: { not: userId } } // Or just those where note is null if not using cascade
|
|
}
|
|
})
|
|
|
|
// Actually, let's just focus on user-specific cleanup
|
|
|
|
// 3. Remove note history entries for notes that were deleted (cascade should handle this, but let's be safe)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
deletedLabels: orphanedLabels.length
|
|
})
|
|
} catch (error) {
|
|
console.error('Cleanup error:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Failed to cleanup data' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|