import type { NextApiRequest, NextApiResponse } from 'next' import sqlite3 from 'sqlite3' import path from 'path' type CheckResponse = { is_problematic: boolean risk_level: number categories: string[] message: string source_count: number } 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 !== 'GET') { return res.status(405).json({ error: 'Method not allowed' }) } const { url } = req.query if (!url || typeof url !== 'string') { return res.status(400).json({ error: 'URL parameter is required' }) } const domain = extractDomain(url) if (!domain) { return res.status(400).json({ error: 'Invalid URL format' }) } const dbPath = path.join(process.cwd(), 'database', 'antihoax.db') const db = new sqlite3.Database(dbPath) try { const sources = await new Promise((resolve, reject) => { db.all( `SELECT s.*, 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.domain = ? AND s.status = 'verified' GROUP BY s.id`, [domain], (err, rows) => { if (err) reject(err) else resolve(rows) } ) }) if (sources.length === 0) { return res.status(200).json({ is_problematic: false, risk_level: 0, categories: [], message: 'Stránka nie je v našej databáze problematických zdrojov', source_count: 0 }) } const maxRiskLevel = Math.max(...sources.map(s => s.risk_level)) const allCategories = sources .map(s => s.categories) .filter(Boolean) .join(',') .split(',') .filter(Boolean) const uniqueCategories = Array.from(new Set(allCategories)) let message = '' if (maxRiskLevel >= 4) { message = 'VYSOKÉ RIZIKO: Táto stránka šíri nebezpečné obsahy' } else if (maxRiskLevel >= 3) { message = 'STREDNÉ RIZIKO: Táto stránka môže obsahovať problematické informácie' } else { message = 'NÍZKE RIZIKO: Táto stránka je označená ako problematická' } return res.status(200).json({ is_problematic: true, risk_level: maxRiskLevel, categories: uniqueCategories, message, source_count: sources.length }) } catch (error) { console.error('Database error:', error) return res.status(500).json({ error: 'Internal server error' }) } finally { db.close() } }