import type { NextApiRequest, NextApiResponse } from "next" import sqlite3 from "sqlite3" import path from "path" export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "GET") return res.status(405).json({ error: "Method not allowed" }) const { format = 'json', type = 'sources' } = req.query const dbPath = path.join(process.cwd(), "database", "antihoax.db") const db = new sqlite3.Database(dbPath) try { let query = "" let filename = "" if (type === 'sources') { query = ` SELECT s.domain, s.risk_level, s.status, s.created_at, GROUP_CONCAT(c.name) as categories FROM sources s LEFT JOIN source_categories sc ON s.id = sc.source_id LEFT JOIN categories c ON sc.category_id = c.id WHERE s.status = 'verified' GROUP BY s.id ORDER BY s.risk_level DESC ` filename = `sources_export_${Date.now()}.${format}` } else if (type === 'reports') { query = ` SELECT source_url, status, categories, description, created_at FROM reports WHERE status != 'spam' ORDER BY created_at DESC ` filename = `reports_export_${Date.now()}.${format}` } const data = await new Promise((resolve, reject) => { db.all(query, (err, rows) => { if (err) reject(err) else resolve(rows) }) }) if (format === 'csv') { // Convert to CSV if (data.length === 0) { return res.status(200).send('') } const headers = Object.keys(data[0]).join(',') const csvRows = data.map(row => Object.values(row).map(value => typeof value === 'string' && value.includes(',') ? `"${value.replace(/"/g, '""')}"` : value ).join(',') ) const csvContent = [headers, ...csvRows].join('\n') res.setHeader('Content-Type', 'text/csv') res.setHeader('Content-Disposition', `attachment; filename="${filename}"`) res.send(csvContent) } else { // JSON format res.setHeader('Content-Type', 'application/json') res.setHeader('Content-Disposition', `attachment; filename="${filename}"`) res.json({ exported_at: new Date().toISOString(), count: data.length, data }) } } catch (error) { console.error('Export error:', error) res.status(500).json({ error: "Export failed" }) } finally { db.close() } }