const { Client } = require('ssh2');
const fs = require('fs');
const path = require('path');

const conn = new Client();

const config = {
  host: '82.22.50.71',
  username: 'slin',
  password: 'motoZ@yaz2010',
  readyTimeout: 30000
};

const localAppJs = path.join(__dirname, 'static', 'app.js');
const localIndexHtml = path.join(__dirname, 'static', 'index.html');
const remoteDir = '/home/slin/enduro-trails/prototype/static/';
const containerName = 'prototype-enduro-trails-1';

console.log('🔌 Connecting to server...');

conn.on('ready', () => {
  console.log('✅ Connected');
  
  conn.sftp((err, sftp) => {
    if (err) {
      console.error('❌ SFTP error:', err);
      conn.end();
      process.exit(1);
    }

    console.log('📤 Uploading app.js...');
    const appJsStream = sftp.createWriteStream(remoteDir + 'app.js');
    fs.createReadStream(localAppJs).pipe(appJsStream);

    appJsStream.on('close', () => {
      console.log('✅ app.js uploaded');

      console.log('📤 Uploading index.html...');
      const indexStream = sftp.createWriteStream(remoteDir + 'index.html');
      fs.createReadStream(localIndexHtml).pipe(indexStream);

      indexStream.on('close', () => {
        console.log('✅ index.html uploaded');

        console.log('🔄 Copying files into container...');
        conn.exec(`docker cp ${remoteDir}app.js ${containerName}:/app/static/app.js && docker cp ${remoteDir}index.html ${containerName}:/app/static/index.html`, (err, stream) => {
          if (err) {
            console.error('❌ Docker cp error:', err);
            conn.end();
            process.exit(1);
          }

          let output = '';
          stream.on('data', (data) => { output += data.toString(); });
          stream.stderr.on('data', (data) => { output += data.toString(); });

          stream.on('close', (code) => {
            if (code !== 0) {
              console.error('❌ Docker cp failed:', output);
              conn.end();
              process.exit(1);
            }
            console.log('✅ Files copied into container');

            console.log('🔄 Restarting container...');
            conn.exec(`docker restart ${containerName}`, (err, stream) => {
              if (err) {
                console.error('❌ Restart error:', err);
                conn.end();
                process.exit(1);
              }

              let restartOutput = '';
              stream.on('data', (data) => { restartOutput += data.toString(); });
              stream.stderr.on('data', (data) => { restartOutput += data.toString(); });

              stream.on('close', (code) => {
                if (code !== 0) {
                  console.error('❌ Restart failed:', restartOutput);
                  conn.end();
                  process.exit(1);
                }
                console.log('✅ Container restarted');
                console.log('🎉 Deploy complete!');
                conn.end();
              });
            });
          });
        });
      });

      indexStream.on('error', (err) => {
        console.error('❌ index.html upload error:', err);
        conn.end();
        process.exit(1);
      });
    });

    appJsStream.on('error', (err) => {
      console.error('❌ app.js upload error:', err);
      conn.end();
      process.exit(1);
    });
  });
});

conn.on('error', (err) => {
  console.error('❌ Connection error:', err);
  process.exit(1);
});

conn.connect(config);
