const fs = require('fs');
const path = require('path');
const sqlite3 = require('sqlite3');
const config = require('../../config/default');

const dbPath = config.db.path;

function backup() {
  const target = `${dbPath}.bak-${Date.now()}`;
  fs.copyFileSync(dbPath, target);
  console.log(`backup created ${target}`);
}

function vacuum() {
  const db = new sqlite3.Database(dbPath);
  db.run('VACUUM', (err) => {
    if (err) {
      console.error('vacuum failed', err.message);
      process.exit(1);
    }
    console.log('vacuum completed');
    db.close();
  });
}

function prune(days = 30) {
  const threshold = Date.now() - days * 24 * 60 * 60 * 1000;
  const timestamp = new Date(threshold).toISOString();
  const db = new sqlite3.Database(dbPath);
  db.run(
    `DELETE FROM delivery_log WHERE created_at < ?`,
    [timestamp],
    function (err) {
      if (err) {
        console.error('prune failed', err.message);
        process.exit(1);
      }
      console.log(`pruned ${this.changes} delivery_log rows older than ${timestamp}`);
      db.close();
    }
  );
}

function usage() {
  console.log('usage: node maintenance.js <backup|vacuum|prune> [--days=<number>]');
}

const args = process.argv.slice(2);
if (!args.length) {
  usage();
  process.exit(0);
}

const command = args[0];
const opts = {};
for (const arg of args.slice(1)) {
  if (arg.startsWith('--days=')) {
    opts.days = Number(arg.replace('--days=', ''));
  }
}

switch (command) {
  case 'backup':
    backup();
    break;
  case 'vacuum':
    vacuum();
    break;
  case 'prune':
    prune(opts.days || 30);
    break;
  default:
    usage();
    process.exit(1);
}
