let db;

function init(database) {
    db = database;
}

function getAll(req, res) {
    db.all(`SELECT * FROM promocodes ORDER BY created_at DESC`, [], (err, rows) => {
        if (err) return res.status(500).json({ error: 'Database error' });
        res.json(rows);
    });
}

function create(req, res) {
    const { code, discount_percent, valid_from, valid_to, valid_days, is_active } = req.body;
    if (!code || !discount_percent) return res.status(400).json({ error: 'Code and discount percent required' });
    if (discount_percent < 1 || discount_percent > 99) return res.status(400).json({ error: 'Discount must be between 1 and 99' });
    db.run(`INSERT INTO promocodes (code, discount_percent, valid_from, valid_to, valid_days, is_active)
            VALUES (?, ?, ?, ?, ?, ?)`,
        [code, discount_percent, valid_from || null, valid_to || null, valid_days || null, is_active !== undefined ? is_active : 1], function(err) {
        if (err) {
            if (err.message.includes('UNIQUE constraint')) return res.status(409).json({ error: 'Promocode already exists' });
            return res.status(500).json({ error: 'Database error' });
        }
        db.get(`SELECT * FROM promocodes WHERE id = ?`, [this.lastID], (err, row) => {
            res.status(201).json({ message: 'Promocode created', promocode: row });
        });
    });
}

function update(req, res) {
    const promoId = parseInt(req.params.id);
    const { code, discount_percent, valid_from, valid_to, valid_days, is_active } = req.body;
    if (discount_percent !== undefined && (discount_percent < 1 || discount_percent > 99)) {
        return res.status(400).json({ error: 'Discount must be between 1 and 99' });
    }
    db.get(`SELECT id FROM promocodes WHERE id = ?`, [promoId], (err, row) => {
        if (err) return res.status(500).json({ error: 'Database error' });
        if (!row) return res.status(404).json({ error: 'Promocode not found' });
        let fields = [];
        let values = [];
        if (code !== undefined) { fields.push('code = ?'); values.push(code); }
        if (discount_percent !== undefined) { fields.push('discount_percent = ?'); values.push(discount_percent); }
        if (valid_from !== undefined) { fields.push('valid_from = ?'); values.push(valid_from || null); }
        if (valid_to !== undefined) { fields.push('valid_to = ?'); values.push(valid_to || null); }
        if (valid_days !== undefined) { fields.push('valid_days = ?'); values.push(valid_days || null); }
        if (is_active !== undefined) { fields.push('is_active = ?'); values.push(is_active); }
        if (fields.length === 0) return res.status(400).json({ error: 'No fields to update' });
        values.push(promoId);
        db.run(`UPDATE promocodes SET ${fields.join(', ')} WHERE id = ?`, values, (err) => {
            if (err) return res.status(500).json({ error: 'Database error' });
            db.get(`SELECT * FROM promocodes WHERE id = ?`, [promoId], (err, row) => {
                res.json({ message: 'Promocode updated', promocode: row });
            });
        });
    });
}

function remove(req, res) {
    const promoId = parseInt(req.params.id);
    db.get(`SELECT id FROM promocodes WHERE id = ?`, [promoId], (err, row) => {
        if (err) return res.status(500).json({ error: 'Database error' });
        if (!row) return res.status(404).json({ error: 'Promocode not found' });
        db.run(`DELETE FROM promocodes WHERE id = ?`, [promoId], (err) => {
            if (err) return res.status(500).json({ error: 'Database error' });
            res.json({ message: 'Promocode deleted' });
        });
    });
}

function setupRoutes(app, authenticateToken, requireAdmin) {
    app.get('/api/admin/promocodes', authenticateToken, requireAdmin, getAll);
    app.post('/api/admin/promocodes', authenticateToken, requireAdmin, create);
    app.put('/api/admin/promocodes/:id', authenticateToken, requireAdmin, update);
    app.delete('/api/admin/promocodes/:id', authenticateToken, requireAdmin, remove);
}

module.exports = { init, setupRoutes };