2025-12-08 16:31:30 +03:00

42 lines
1.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getAllPolls } from '@/lib/polls'
export async function GET(req: NextRequest) {
try {
const { searchParams } = new URL(req.url)
const filter = searchParams.get('filter') || 'trending'
const search = searchParams.get('search') || ''
let polls = await getAllPolls()
// Search filter
if (search) {
const query = search.toLowerCase()
polls = polls.filter(poll =>
poll.question.toLowerCase().includes(query) ||
poll.description?.toLowerCase().includes(query) ||
poll.options.some(opt => opt.text.toLowerCase().includes(query))
)
}
// Sort by filter
if (filter === 'trending') {
const now = Date.now()
polls.sort((a, b) => {
const aScore = (a.totalVotes / Math.max(1, (now - a.createdAt) / 3600000)) * a.totalAmount
const bScore = (b.totalVotes / Math.max(1, (now - b.createdAt) / 3600000)) * b.totalAmount
return bScore - aScore
})
} else if (filter === 'recent') {
polls.sort((a, b) => b.createdAt - a.createdAt)
} else if (filter === 'popular') {
polls.sort((a, b) => b.totalVotes - a.totalVotes)
}
return NextResponse.json({ polls })
} catch (error) {
console.error('Polls API error:', error)
return NextResponse.json({ polls: [] })
}
}