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

function lockingStand(user, data) {
    return new Promise((resolve, reject) => {
        const sheepId = Number(data.sheep_id) || null;
        
        if (!user.possibilities.can_view_stand) {
            return reject(new Error("Forbidden: no rights to view stand"));
        }
        if ((sheepId !== user.id && sheepId !== null) && !user.possibilities.can_manager_stand) {
            return reject(new Error("Forbidden: no rights to view stand"));
        }

        resolve({ update: "ok", id: data.id });
    });
}

function unlockingStand(user, data) {
    return new Promise((resolve, reject) => {
        const sheepId = Number(data.sheep_id) || null;
        
        if (!user.possibilities.can_view_stand) {
            return reject(new Error("Forbidden: no rights to view stand"));
        }
        if ((sheepId !== user.id && sheepId !== null) && !user.possibilities.can_manager_stand) {
            return reject(new Error("Forbidden: no rights to view stand"));
        }

        resolve({ update: "ok", id: data.id });
    });
}

function updateStand(user, data) {
    return new Promise((resolve, reject) => {
        const sheepId = Number(data.sheep_id) || null;
        
        if (!user.possibilities.can_view_stand) {
            return reject(new Error("Forbidden: no rights to view stand"));
        }
        if ((sheepId !== user.id && sheepId !== null) && !user.possibilities.can_manager_stand) {
            return reject(new Error("Forbidden: no rights to view stand"));
        }

        const sql = `
            UPDATE stand_schedule 
            SET sheep_id = ?, updated_at = ? 
            WHERE id = ?`;

        db.run(sql, [sheepId, Date.now(), data.id], function (err) {
            if (err) return reject(err);
            if (this.changes === 0) return reject(new Error("Stand not found"));

            const insertSql = `
                INSERT INTO stand_schedule_history 
                (stand_schedule_id, sheep_id, created_at) 
                VALUES (?, ?, ?)`;

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

module.exports = { lockingStand, unlockingStand, updateStand };