const fs = require('fs');
const path = require('path');
const pty = require('node-pty');
const { User } = require('../models/user');
const { sendMessage } = require('../telegram/api');

function setupShellWebSocket(ws) {
  console.log('🔌 Client WebSocket Shell connesso');
  let scriptProcess = null;
  let buffer = '';

  ws.on('message', async (message) => {
    try {
      const parsed = JSON.parse(message);
      const { type, user_id, scriptName, data } = parsed;

      if (type === 'start_script' && (await User.isAdminById(user_id))) {
        if (scriptProcess) scriptProcess.kill();

        const scriptPath = path.join(__dirname, '..', '..', scriptName);
        if (!fs.existsSync(scriptPath)) {
          return ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato' }));
        }

        scriptProcess = pty.spawn('bash', [scriptPath], {
          name: 'xterm-color',
          cols: 80,
          rows: 40,
          cwd: process.cwd(),
          env: process.env,
        });

        scriptProcess.on('data', (chunk) => {
          buffer += chunk;
          ws.send(JSON.stringify({ type: 'output', data: chunk }));
          if (buffer.length > 4096) buffer = buffer.slice(-2048);
        });

        scriptProcess.on('exit', (code) => {
          const msg = code === 0 ? '✅ Script completato' : `❌ Uscito con codice ${code}`;
          ws.send(JSON.stringify({ type: 'close', data: msg }));
        });
      } else if (type === 'input' && scriptProcess) {
        scriptProcess.write(data + '\n');
      }
    } catch (err) {
      console.error('❌ Errore WS Shell:', err.message);
    }
  });

  ws.on('close', () => {
    if (scriptProcess) scriptProcess.kill();
    console.log('🔌 WS Shell chiuso');
  });
}

module.exports = { setupShellWebSocket };
