import type { NextApiRequest, NextApiResponse } from "next" import { db, schema } from '../../../lib/db/connection' import { count, gte, eq } from 'drizzle-orm' export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "GET") return res.status(405).json({ error: "Method not allowed" }) try { // Get performance metrics const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) const [ totalSources, verifiedSources, highRiskSources, sourcesLastWeek ] = await Promise.all([ db.select({ count: count() }).from(schema.sources), db.select({ count: count() }).from(schema.sources).where(eq(schema.sources.status, 'verified')), db.select({ count: count() }).from(schema.sources).where(gte(schema.sources.riskLevel, 4)), db.select({ count: count() }).from(schema.sources).where(gte(schema.sources.createdAt, weekAgo)) ]) // Get API usage simulation const apiUsage = { daily_requests: Math.floor(Math.random() * 10000) + 5000, avg_response_time: Math.floor(Math.random() * 150) + 50, error_rate: Math.random() * 0.05 } res.json({ database_stats: { total_sources: totalSources[0].count, verified_sources: verifiedSources[0].count, high_risk_sources: highRiskSources[0].count, sources_last_week: sourcesLastWeek[0].count }, api_performance: apiUsage, last_updated: new Date().toISOString() }) } catch (error) { console.error('Analytics error:', error) res.status(500).json({ error: "Failed to fetch analytics" }) } }