const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

// Load environment variables from .env file
const envPath = path.join(__dirname, '..', '.env');
if (fs.existsSync(envPath)) {
  const envContent = fs.readFileSync(envPath, 'utf8');
  envContent.split('\n').forEach(line => {
    const [key, ...valueParts] = line.split('=');
    if (key && valueParts.length > 0) {
      const value = valueParts.join('=').trim();
      if (value.startsWith('"') && value.endsWith('"')) {
        process.env[key.trim()] = value.slice(1, -1);
      } else {
        process.env[key.trim()] = value;
      }
    }
  });
}

const DATABUCKET_DIR = path.join(__dirname, '..', 'databucket');

// Ensure databucket directory exists
if (!fs.existsSync(DATABUCKET_DIR)) {
  fs.mkdirSync(DATABUCKET_DIR, { recursive: true });
}

// Delete old backup files
const files = fs.readdirSync(DATABUCKET_DIR).filter(file => file.startsWith('backup_') && file.endsWith('.sql'));
files.forEach(file => {
  fs.unlinkSync(path.join(DATABUCKET_DIR, file));
});

// Generate timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const filename = `backup_${timestamp}.sql`;
const filepath = path.join(DATABUCKET_DIR, filename);

// Database credentials from environment
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
  console.error('DATABASE_URL not found in environment variables');
  process.exit(1);
}

// Parse MySQL URL
// mysql://root:@localhost:3306/propmaster_db
const urlMatch = dbUrl.match(/mysql:\/\/([^:]*):?([^@]*)@([^:]+):(\d+)\/(.+)/);
if (!urlMatch) {
  console.error('Invalid DATABASE_URL format');
  process.exit(1);
}

const [, user, password, host, port, database] = urlMatch;

// Construct mysqldump command
// For XAMPP on Windows, mysqldump is typically at C:\xampp\mysql\bin\mysqldump.exe
const mysqldumpPath = process.platform === 'win32' ? 'C:\\xampp\\mysql\\bin\\mysqldump.exe' : 'mysqldump';
const dumpCommand = `"${mysqldumpPath}" -h ${host} -P ${port} -u ${user} ${password ? `-p${password}` : ''} ${database} > "${filepath}"`;

console.log('Starting database backup...');

exec(dumpCommand, (error, stdout, stderr) => {
  if (error) {
    console.error('Error creating backup:', error);
    console.error('stderr:', stderr);
    process.exit(1);
  }

  console.log('Database backup completed successfully:', filename);

  // Verify file was created
  if (fs.existsSync(filepath)) {
    const stats = fs.statSync(filepath);
    console.log(`Backup file size: ${stats.size} bytes`);
  } else {
    console.error('Backup file was not created');
    process.exit(1);
  }
});