import type { NextApiRequest, NextApiResponse } from 'next' import { db, schema } from '../../lib/db/connection' function extractDomain(url: string): string { try { const urlObj = new URL(url) return urlObj.hostname.replace('www.', '') } catch { return '' } } export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }) } const { source_url, reporter_email, reporter_name, description, categories } = req.body if (!source_url || !description) { return res.status(400).json({ error: 'URL and description are required' }) } const domain = extractDomain(source_url) if (!domain) { return res.status(400).json({ error: 'Invalid URL format' }) } try { await db.insert(schema.reports).values({ sourceUrl: source_url, sourceDomain: domain, reporterEmail: reporter_email || null, reporterName: reporter_name || null, categorySuggestions: JSON.stringify(categories || []), description: description, ipAddress: (req.headers['x-forwarded-for'] as string) || (req.socket?.remoteAddress), userAgent: req.headers['user-agent'] || null }) return res.status(200).json({ success: true, message: 'Report submitted successfully' }) } catch (error) { console.error('Database error:', error) return res.status(500).json({ error: 'Internal server error' }) } }