let db;

function init(database) { db = database; }

function setupRoutes(app, auth) {
    const { authenticateToken, requireAdmin } = auth;

    app.get('/api/admin/leads', authenticateToken, requireAdmin, (req, res) => {
        const page = parseInt(req.query.page) || 1;
        const limit = 20;
        const offset = (page - 1) * limit;
        const search = req.query.search || '';

        let where = '';
        const params = [];
        if (search) {
            where = `WHERE name LIKE ? OR phone LIKE ? OR message LIKE ?`;
            params.push(`%${search}%`, `%${search}%`, `%${search}%`);
        }

        db.get(`SELECT COUNT(*) as total FROM leads ${where}`, params, (err, countRow) => {
            if (err) return res.status(500).json({ error: 'Ошибка БД' });
            const total = countRow.total;
            db.all(`SELECT * FROM leads ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
                [...params, limit, offset], (err2, rows) => {
                    if (err2) return res.status(500).json({ error: 'Ошибка БД' });
                    res.json({ data: rows, total, page, totalPages: Math.ceil(total / limit) });
                });
        });
    });

    app.delete('/api/admin/leads/:id', authenticateToken, requireAdmin, (req, res) => {
        const id = parseInt(req.params.id);
        if (isNaN(id)) return res.status(400).json({ error: 'Неверный ID' });
        const stmt = db.prepare(`DELETE FROM leads WHERE id = ?`);
        stmt.run(id, function(err) {
            if (err) return res.status(500).json({ error: 'Ошибка удаления' });
            if (this.changes === 0) return res.status(404).json({ error: 'Не найдено' });
            res.json({ message: 'Заявка удалена' });
        });
        stmt.finalize();
    });
}

module.exports = { init, setupRoutes };
