const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
const archiver = require('archiver');
const dotenv = require('dotenv');

// Load environment variables based on NODE_ENV
const envFile =
  process.env.NODE_ENV === 'production'
    ? '.env.production'
    : '.env.development';
dotenv.config({ path: path.join(__dirname, '..', envFile) });

// Function to create and send zip file
function sendZipFile() {
  return new Promise((resolve, reject) => {
    const distPath = path.join(__dirname, '../dist');
    const zipPath = path.join(__dirname, '../dist.zip');

    // Create a file to stream archive data to
    const output = fs.createWriteStream(zipPath);
    const archive = archiver('zip', {
      zlib: { level: 9 }, // Sets the compression level
    });

    // Listen for all archive data to be written
    output.on('close', () => {
      console.log(`✅ Archive created: ${archive.pointer()} total bytes`);

      // Get the deployment URL from environment
      const deployUrl = process.env.VITE_DEPLOY_URL;
      if (!deployUrl) {
        console.error('❌ VITE_DEPLOY_URL not found in environment variables');
        process.exit(1);
      }

      // Send the zip file via curl
      try {
        console.log(`📤 Sending zip file to ${deployUrl}...`);
        execSync(`curl -X POST -F "file=@${zipPath}" ${deployUrl}`, {
          stdio: 'inherit',
        });
        console.log('✅ Zip file sent successfully');
      } catch (error) {
        console.error('❌ Failed to send zip file:', error.message);
        process.exit(1);
      }

      // Clean up the zip file
      fs.unlinkSync(zipPath);
      resolve();
    });

    // Handle warnings and errors
    archive.on('warning', err => {
      if (err.code === 'ENOENT') {
        console.warn('⚠️ Archive warning:', err);
      } else {
        reject(err);
      }
    });

    archive.on('error', err => {
      reject(err);
    });

    // Pipe archive data to the file
    archive.pipe(output);

    // Add the dist directory to the archive
    archive.directory(distPath, false);

    // Finalize the archive
    archive.finalize();
  });
}

// Run the deployment
sendZipFile()
  .then(() => {
    console.log('✅ Deployment successful!');
  })
  .catch(error => {
    console.error('❌ Deployment failed:', error.message);
    process.exit(1);
  });
