let db;

function init(database) {
    db = database;
}

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

function create(req, res) {
    const { room_type, date_from, date_to, price_per_night, label, is_active } = req.body;
    if (!room_type || !date_from || !date_to || !price_per_night) {
        return res.status(400).json({ error: 'room_type, date_from, date_to и price_per_night обязательны' });
    }
    if (new Date(date_to) <= new Date(date_from)) {
        return res.status(400).json({ error: 'date_to должна быть позже date_from' });
    }
    db.run(
        `INSERT INTO seasonal_prices (room_type, date_from, date_to, price_per_night, label, is_active) VALUES (?, ?, ?, ?, ?, ?)`,
        [room_type, date_from, date_to, price_per_night, label || null, is_active !== undefined ? (is_active ? 1 : 0) : 1],
        function(err) {
            if (err) return res.status(500).json({ error: 'Database error' });
            db.get(`SELECT * FROM seasonal_prices WHERE id = ?`, [this.lastID], (err, row) => {
                if (err) return res.status(500).json({ error: 'Database error' });
                res.status(201).json(row);
            });
        }
    );
}

function update(req, res) {
    const { id } = req.params;
    const { room_type, date_from, date_to, price_per_night, label, is_active } = req.body;

    db.get(`SELECT * FROM seasonal_prices WHERE id = ?`, [id], (err, row) => {
        if (err) return res.status(500).json({ error: 'Database error' });
        if (!row) return res.status(404).json({ error: 'Не найдено' });

        const newRoomType = room_type ?? row.room_type;
        const newDateFrom = date_from ?? row.date_from;
        const newDateTo = date_to ?? row.date_to;

        if (new Date(newDateTo) <= new Date(newDateFrom)) {
            return res.status(400).json({ error: 'date_to должна быть позже date_from' });
        }

        db.run(
            `UPDATE seasonal_prices SET room_type=?, date_from=?, date_to=?, price_per_night=?, label=?, is_active=? WHERE id=?`,
            [newRoomType, newDateFrom, newDateTo,
             price_per_night ?? row.price_per_night,
             label !== undefined ? label : row.label,
             is_active !== undefined ? (is_active ? 1 : 0) : row.is_active,
             id],
            function(err) {
                if (err) return res.status(500).json({ error: 'Database error' });
                db.get(`SELECT * FROM seasonal_prices WHERE id = ?`, [id], (err, row) => {
                    if (err) return res.status(500).json({ error: 'Database error' });
                    res.json(row);
                });
            }
        );
    });
}

function remove(req, res) {
    const { id } = req.params;
    db.run(`DELETE FROM seasonal_prices WHERE id = ?`, [id], function(err) {
        if (err) return res.status(500).json({ error: 'Database error' });
        if (this.changes === 0) return res.status(404).json({ error: 'Не найдено' });
        res.json({ message: 'Сезонная цена удалена' });
    });
}

function getSeasonalPrice(roomType, date, callback) {
    db.get(
        `SELECT price_per_night FROM seasonal_prices WHERE room_type = ? AND is_active = 1 AND date_from <= ? AND date_to >= ? ORDER BY date_from DESC LIMIT 1`,
        [roomType, date, date],
        (err, row) => {
            if (err) return callback(err, null);
            callback(null, row ? row.price_per_night : null);
        }
    );
}

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

module.exports = { init, setupRoutes, getSeasonalPrice };
