import type { NextApiRequest, NextApiResponse } from 'next' import { db, schema } from '../../../lib/db/connection' import { eq, and, gte, count } from 'drizzle-orm' interface DashboardStats { total_sources: number pending_sources: number pending_reports: number high_risk_sources: number sources_added_week: number reports_today: number } export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method !== 'GET') { return res.status(405).json({ error: 'Method not allowed' }) } try { // Get all stats in parallel const weekAgo = new Date() weekAgo.setDate(weekAgo.getDate() - 7) const dayAgo = new Date() dayAgo.setDate(dayAgo.getDate() - 1) const [ totalSources, pendingSources, pendingReports, highRiskSources, sourcesAddedWeek, reportsToday ] = await Promise.all([ db.select({ count: count() }) .from(schema.sources) .where(eq(schema.sources.status, 'verified')), db.select({ count: count() }) .from(schema.sources) .where(eq(schema.sources.status, 'pending')), db.select({ count: count() }) .from(schema.reports) .where(eq(schema.reports.status, 'pending')), db.select({ count: count() }) .from(schema.sources) .where( and( eq(schema.sources.status, 'verified'), gte(schema.sources.riskLevel, 4) ) ), db.select({ count: count() }) .from(schema.sources) .where(gte(schema.sources.createdAt, weekAgo)), db.select({ count: count() }) .from(schema.reports) .where(gte(schema.reports.createdAt, dayAgo)) ]) const stats: DashboardStats = { total_sources: totalSources[0].count, pending_sources: pendingSources[0].count, pending_reports: pendingReports[0].count, high_risk_sources: highRiskSources[0].count, sources_added_week: sourcesAddedWeek[0].count, reports_today: reportsToday[0].count } return res.status(200).json(stats) } catch (error) { console.error('Database error:', error) return res.status(500).json({ error: 'Internal server error' }) } }