import type { NextApiRequest, NextApiResponse } from "next" import { db, schema } from '../../../lib/db/connection' import { eq, desc, count } 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" }) const { status = 'verified', page = '1', limit = '20' } = req.query try { // Pagination const pageNum = parseInt(page as string) const limitNum = parseInt(limit as string) const offset = (pageNum - 1) * limitNum const results = await db.select({ id: schema.sources.id, domain: schema.sources.domain, title: schema.sources.title, description: schema.sources.description, type: schema.sources.type, status: schema.sources.status, riskLevel: schema.sources.riskLevel, createdAt: schema.sources.createdAt, }) .from(schema.sources) .where(eq(schema.sources.status, status as any)) .orderBy(desc(schema.sources.createdAt)) .limit(limitNum) .offset(offset) // Get total count const totalResult = await db.select({ count: count() }) .from(schema.sources) .where(eq(schema.sources.status, status as any)) const total = totalResult[0].count res.json({ results, pagination: { page: pageNum, limit: limitNum, total, pages: Math.ceil(total / limitNum) } }) } catch (error) { console.error('Advanced search error:', error) res.status(500).json({ error: "Search failed" }) } }