let db;

function init(database) { db = database; }

function loadEquipmentGallery(data) {
    return new Promise((resolve) => {
        db.all(`SELECT * FROM equipment_gallery ORDER BY equipment_id, sort_order`, (err, rows) => {
            if (err || !rows) { data.equipment_gallery = []; resolve(); return; }
            data.equipment_gallery = rows;
            resolve();
        });
    });
}

function setupRoutes(app) {
    app.get('/api/site-data', (req, res) => {
        const data = {};

        function loadTable(table, key) {
            return new Promise((resolve) => {
                db.all(`SELECT * FROM ${table} ORDER BY sort_order`, (err, rows) => {
                    if (err) { data[key] = []; resolve(); return; }
                    if (table === 'equipment' || table === 'partners') {
                        rows = rows.filter(r => r.is_active == 1);
                    }
                    if (table === 'services' || table === 'work_schemes') {
                        rows = rows.filter(r => r.is_active == 1);
                    }
                    data[key] = rows;
                    resolve();
                });
            });
        }

        function loadSettings(table, key, transformFn) {
            return new Promise((resolve) => {
                db.all(`SELECT * FROM ${table} ORDER BY id`, (err, rows) => {
                    if (err) { data[key] = {}; resolve(); return; }
                    if (transformFn) {
                        data[key] = transformFn(rows);
                    } else {
                        const obj = {};
                        rows.forEach(r => { obj[r.key] = r.value; });
                        data[key] = obj;
                    }
                    resolve();
                });
            });
        }

        Promise.all([
            loadSettings('hero_settings', 'hero'),
            loadTable('hero_stats', 'hero_stats'),
            loadSettings('about_settings', 'about'),
            loadTable('about_features', 'about_features'),
            loadTable('services', 'services'),
            loadTable('work_schemes', 'work_schemes'),
            loadTable('process_steps', 'process_steps'),
            loadTable('equipment', 'equipment'),
            loadEquipmentGallery(data),
            loadTable('geo_regions', 'geo_regions'),
            loadSettings('geo_settings', 'geo'),
            loadTable('licenses', 'licenses'),
            loadTable('license_gallery', 'license_gallery'),
            loadTable('public_activities', 'public_activities'),
            loadTable('activity_gallery', 'activity_gallery'),
            loadTable('partners', 'partners'),
            loadSettings('settings', 'settings')
        ]).then(() => {
            res.json(data);
        });
    });

    app.post('/api/leads', (req, res) => {
        const { name, phone, message } = req.body;
        if (!name || !phone) return res.status(400).json({ error: 'Имя и телефон обязательны' });
        const stmt = db.prepare(`INSERT INTO leads (name, phone, message) VALUES (?, ?, ?)`);
        stmt.run(name.trim(), phone.trim(), (message || '').trim(), function(err) {
            if (err) return res.status(500).json({ error: 'Ошибка БД' });
            res.status(201).json({ id: this.lastID, message: 'Заявка сохранена' });
        });
        stmt.finalize();
    });
}

module.exports = { init, setupRoutes };
