const db = require("../config/db");

function updateBuilding(user, data) {
    return new Promise((resolve, reject) => {
        if (!user.possibilities.can_view_territory) {
            return reject(new Error("Forbidden: no rights to manage territory"));
        }

        const sql = `
            UPDATE buildings 
            SET status = ?, description = ?, sheep_id = ?, updated_at = ? 
            WHERE id = ?`;

        db.run(sql, [Number(data.status), data.description, user.id, data.updated_at, data.id], function (err) {
            if (err) return reject(err);
            if (this.changes === 0) return reject(new Error("Building not found"));

            const insertSql = `
                INSERT INTO buildings_history 
                (buildings_id, status, description, sheep_id, created_at) 
                VALUES (?, ?, ?, ?, ?)`;

            db.run(insertSql, [Number(data.id), Number(data.status), data.description, user.id, Date.now()], function (err) {
                if (err) return reject(err);
                resolve({ update: "ok", id: data.id, historyId: this.lastID });
            });
        });
    });
}

module.exports = { updateBuilding };