import type { NextApiRequest, NextApiResponse } from 'next' import { db, schema } from '../../lib/db/connection' import { eq, gte, count, desc, sql } from 'drizzle-orm' interface PublicStats { total_sources: number high_risk_sources: number categories_breakdown: { [key: string]: number } recent_additions: number top_domains: { domain: string; count: number; risk_level: 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 basic counts const [totalSourcesResult] = await db .select({ count: count() }) .from(schema.sources) .where(eq(schema.sources.status, 'verified')) const [highRiskSourcesResult] = await db .select({ count: count() }) .from(schema.sources) .where( sql`${schema.sources.status} = 'verified' AND ${schema.sources.riskLevel} >= 4` ) const thirtyDaysAgo = new Date() thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30) const [recentAdditionsResult] = await db .select({ count: count() }) .from(schema.sources) .where(gte(schema.sources.createdAt, thirtyDaysAgo)) // Get categories breakdown const categoriesBreakdownResult = await db .select({ name: schema.categories.name, count: count() }) .from(schema.categories) .innerJoin(schema.sourceCategories, eq(schema.categories.id, schema.sourceCategories.categoryId)) .innerJoin(schema.sources, eq(schema.sourceCategories.sourceId, schema.sources.id)) .where(eq(schema.sources.status, 'verified')) .groupBy(schema.categories.id, schema.categories.name) const categoriesBreakdown: { [key: string]: number } = {} categoriesBreakdownResult.forEach(row => { categoriesBreakdown[row.name] = row.count }) // Get top risky domains const topDomainsResult = await db .select({ domain: schema.sources.domain, count: count(), avgRisk: sql`AVG(${schema.sources.riskLevel})` }) .from(schema.sources) .where(eq(schema.sources.status, 'verified')) .groupBy(schema.sources.domain) .orderBy(desc(sql`AVG(${schema.sources.riskLevel})`), desc(count())) .limit(10) const topDomains = topDomainsResult.map(row => ({ domain: row.domain, count: row.count, risk_level: Math.round(row.avgRisk * 10) / 10 })) const stats: PublicStats = { total_sources: totalSourcesResult.count, high_risk_sources: highRiskSourcesResult.count, categories_breakdown: categoriesBreakdown, recent_additions: recentAdditionsResult.count, top_domains: topDomains } return res.status(200).json(stats) } catch (error) { console.error('Database error:', error) return res.status(500).json({ error: 'Internal server error' }) } }