Files
cbd420/app/api/referral-points/route.ts
2025-12-31 07:49:35 +00:00

66 lines
1.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import pool from '@/lib/db'
// GET /api/referral-points - Get current user's referral points and settings
export async function GET(request: NextRequest) {
try {
const cookieStore = await cookies()
const buyerIdCookie = cookieStore.get('buyer_id')?.value
if (!buyerIdCookie) {
return NextResponse.json(
{ error: 'Authentication required' },
{ status: 401 }
)
}
const buyer_id = parseInt(buyerIdCookie, 10)
// Get buyer's referral points
const [buyerRows] = await pool.execute(
'SELECT referral_points FROM buyers WHERE id = ?',
[buyer_id]
)
const buyers = buyerRows as any[]
if (buyers.length === 0) {
return NextResponse.json(
{ error: 'Buyer not found' },
{ status: 404 }
)
}
const referralPoints = parseFloat(buyers[0].referral_points) || 0
// Get referral settings
const [settingsRows] = await pool.execute(
'SELECT setting_key, setting_value FROM referral_settings'
)
const settings = settingsRows as any[]
const pointsToChf = parseFloat(
settings.find(s => s.setting_key === 'points_to_chf')?.setting_value || '100'
)
const pointsPerChf = parseFloat(
settings.find(s => s.setting_key === 'points_per_chf')?.setting_value || '10'
)
// Calculate maximum discount available
const maxDiscountChf = referralPoints / pointsToChf
return NextResponse.json({
referral_points: referralPoints,
points_to_chf: pointsToChf,
points_per_chf: pointsPerChf,
max_discount_chf: maxDiscountChf,
})
} catch (error) {
console.error('Error fetching referral points:', error)
return NextResponse.json(
{ error: 'Failed to fetch referral points' },
{ status: 500 }
)
}
}