const { updateApartment } = require("../services/apartments.service");
const { updateBuilding } = require("../services/buildings.service");
const { lockingStand, unlockingStand, updateStand } = require("../services/stand.service");
const { broadcast } = require("../utils/broadcaster");

module.exports = async (wss, ws, message) => {
    try {
        switch (message.type) {
            case "apartment":
                await updateApartment(ws.user, message.data);
                break;
            case "building":
                await updateBuilding(ws.user, message.data);
                break;
            case "stand_locking":
                await lockingStand(ws.user, message.data);
                if(!message.data.sheep_name) message.data.sheep_name = ws.user.name;
                break;
            case "stand_unlocking":
                await unlockingStand(ws.user, message.data);
                if(!message.data.sheep_name) message.data.sheep_name = ws.user.name;
                break;
            case "stand_update":
                await updateStand(ws.user, message.data);
                if(!message.data.sheep_name) message.data.sheep_name = ws.user.name;
                break;
            default:
                return ws.send(JSON.stringify({ error: `Unknown message type: ${message.type}` }));
        }
        broadcast(wss, message);
    } catch (err) {
        ws.send(JSON.stringify({ error: err.message }));
    }
};