pummmp.fun/app/api/rewards/route.ts
2026-07-04 12:49:09 -07:00

104 lines
3.4 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { connectToDatabase } from '@/lib/mongodb'
import { ObjectId } from 'mongodb'
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { db } = await connectToDatabase()
const user = await db.collection('users').findOne({ _id: new ObjectId(session.user.id) })
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}
// Check cooling period (24 hours)
const lastClaim = user.lastDailyRewardClaim ? new Date(user.lastDailyRewardClaim) : null
const now = new Date()
if (lastClaim) {
const diffTime = Math.abs(now.getTime() - lastClaim.getTime())
const diffHours = Math.ceil(diffTime / (1000 * 60 * 60))
if (diffTime < 24 * 60 * 60 * 1000) {
const remainingMs = (24 * 60 * 60 * 1000) - diffTime;
return NextResponse.json({
error: 'Daily reward already claimed',
nextClaim: new Date(now.getTime() + remainingMs)
}, { status: 400 })
}
}
// Fetch SOL price to calculate $100 equivalent
let solPrice = 120; // Default fallback
try {
const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd')
if (response.ok) {
const data = await response.json()
solPrice = data.solana.usd
}
} catch (e) {
console.error("Failed to fetch SOL price", e)
}
const rewardAmountSol = 100 / solPrice
await db.collection('users').updateOne(
{ _id: new ObjectId(session.user.id) },
{
$inc: { balance: rewardAmountSol },
$set: { lastDailyRewardClaim: now }
}
)
return NextResponse.json({
success: true,
amount: rewardAmountSol,
newBalance: user.balance + rewardAmountSol
})
} catch (error) {
console.error('Reward claim error:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
export async function GET(request: NextRequest) {
// Get status
try {
const session = await getServerSession(authOptions)
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { db } = await connectToDatabase()
const user = await db.collection('users').findOne({ _id: new ObjectId(session.user.id) })
if (!user) return NextResponse.json({ error: 'User not found'}, { status: 404 })
const lastClaim = user.lastDailyRewardClaim ? new Date(user.lastDailyRewardClaim) : null
let canClaim = true
let nextClaimTime = null
if (lastClaim) {
const now = new Date()
const diff = now.getTime() - lastClaim.getTime()
if (diff < 24 * 60 * 60 * 1000) {
canClaim = false
nextClaimTime = new Date(lastClaim.getTime() + 24 * 60 * 60 * 1000)
}
}
return NextResponse.json({ canClaim, nextClaimTime })
} catch (error) {
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}