47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
|
|
import { NextRequest, NextResponse } from 'next/server'
|
||
|
|
import { prisma } from '@/lib/prisma'
|
||
|
|
import { verifyJWT } from '@/lib/auth'
|
||
|
|
|
||
|
|
export async function POST(req: NextRequest) {
|
||
|
|
try {
|
||
|
|
const auth = req.headers.get('authorization')
|
||
|
|
if (!auth?.startsWith('Bearer ')) {
|
||
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||
|
|
}
|
||
|
|
|
||
|
|
const payload = await verifyJWT(auth.slice(7))
|
||
|
|
if (!payload) {
|
||
|
|
return NextResponse.json({ error: 'Invalid token' }, { status: 401 })
|
||
|
|
}
|
||
|
|
|
||
|
|
const { projectId, amountFlh } = await req.json()
|
||
|
|
if (!projectId || !amountFlh || amountFlh <= 0) {
|
||
|
|
return NextResponse.json({ error: 'Invalid project or amount' }, { status: 400 })
|
||
|
|
}
|
||
|
|
|
||
|
|
const user = await prisma.user.findUnique({ where: { id: payload.id } })
|
||
|
|
if (!user) {
|
||
|
|
return NextResponse.json({ error: 'User not found' }, { status: 404 })
|
||
|
|
}
|
||
|
|
|
||
|
|
if (user.flhBalance < amountFlh) {
|
||
|
|
return NextResponse.json({ error: 'Insufficient FLH balance' }, { status: 400 })
|
||
|
|
}
|
||
|
|
|
||
|
|
// Decrement the user's balance
|
||
|
|
const updatedUser = await prisma.user.update({
|
||
|
|
where: { id: payload.id },
|
||
|
|
data: { flhBalance: { decrement: amountFlh } },
|
||
|
|
})
|
||
|
|
|
||
|
|
return NextResponse.json({
|
||
|
|
success: true,
|
||
|
|
newBalance: updatedUser.flhBalance,
|
||
|
|
message: `Successfully contributed ${amountFlh} FLH to the project.`
|
||
|
|
})
|
||
|
|
} catch (e) {
|
||
|
|
console.error(e)
|
||
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||
|
|
}
|
||
|
|
}
|