34 lines
985 B
TypeScript
34 lines
985 B
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { requireAdmin } from '@/lib/auth'
|
|
import { getUserById, deleteUser, listUsers } from '@/lib/users'
|
|
|
|
export async function DELETE(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const auth = await requireAdmin(request)
|
|
if (auth instanceof NextResponse) return auth
|
|
const { session } = auth
|
|
|
|
const { id } = await params
|
|
|
|
if (id === session.userId) {
|
|
return NextResponse.json({ error: 'Cannot delete your own account' }, { status: 409 })
|
|
}
|
|
|
|
const target = getUserById(id)
|
|
if (!target) {
|
|
return NextResponse.json({ error: 'User not found' }, { status: 404 })
|
|
}
|
|
|
|
if (target.role === 'admin') {
|
|
const admins = listUsers().filter((u) => u.role === 'admin')
|
|
if (admins.length <= 1) {
|
|
return NextResponse.json({ error: 'Cannot delete the last admin account' }, { status: 409 })
|
|
}
|
|
}
|
|
|
|
deleteUser(id)
|
|
return new NextResponse(null, { status: 204 })
|
|
}
|