// routes/backup.js
const express = require('express');
const router  = express.Router();
const fs      = require('fs');
const path    = require('path');
//const archiver = require('archiver');
const { exec } = require('child_process');

const BACKUP_DIR = path.join(__dirname, '..', 'backups');

// Ensure backup dir exists
if (!fs.existsSync(BACKUP_DIR)) fs.mkdirSync(BACKUP_DIR, { recursive: true });

// ── List backups ─────────────────────────────────────────
router.get('/list', (req, res) => {
  try {
    const files = fs.readdirSync(BACKUP_DIR)
      .filter(f => f.endsWith('.zip') || f.endsWith('.bak') || f.endsWith('.tar'))
      .map(f => {
        const full = path.join(BACKUP_DIR, f);
        const stat = fs.statSync(full);
        return {
          name    : f,
          size    : stat.size,
          created : stat.birthtime,
          modified: stat.mtime,
          type    : path.extname(f).replace('.', '').toUpperCase()
        };
      })
      .sort((a, b) => new Date(b.created) - new Date(a.created));
    res.json({ ok: true, backups: files, dir: BACKUP_DIR });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Create backup (ZIP a folder) ────────────────────────
router.post('/create', (req, res) => {
    const archiver = require('archiver');
  const { source, name, note } = req.body;
  if (!source || !name) return res.json({ ok: false, error: 'source and name are required' });

  if (!fs.existsSync(source))
    return res.json({ ok: false, error: `Source path does not exist: ${source}` });

  const ts      = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
  const safeName = name.replace(/[^a-zA-Z0-9_\-]/g, '_');
  const outFile  = path.join(BACKUP_DIR, `${safeName}_${ts}.zip`);
  const output   = fs.createWriteStream(outFile);
  const archive  = archiver('zip', { zlib: { level: 6 } });

  output.on('close', () => {
    const stat = fs.statSync(outFile);
    res.json({ ok: true, file: path.basename(outFile), size: stat.size });
  });

  archive.on('error', err => {
    res.json({ ok: false, error: err.message });
  });

  archive.pipe(output);

  const srcStat = fs.statSync(source);
  if (srcStat.isDirectory()) {
    archive.directory(source, false);
  } else {
    archive.file(source, { name: path.basename(source) });
  }

  // Save metadata note file alongside backup
  if (note) {
    const meta = { source, name, note, created: new Date().toISOString() };
    fs.writeFileSync(outFile.replace('.zip', '.meta.json'), JSON.stringify(meta, null, 2));
  }

  archive.finalize();
});

// ── Delete backup ────────────────────────────────────────
router.delete('/:filename', (req, res) => {
  try {
    const file = req.params.filename;
    // Prevent path traversal
    if (file.includes('..') || file.includes('/') || file.includes('\\'))
      return res.json({ ok: false, error: 'Invalid filename' });

    const full = path.join(BACKUP_DIR, file);
    if (!fs.existsSync(full)) return res.json({ ok: false, error: 'File not found' });

    fs.unlinkSync(full);

    // Also remove meta file if present
    const meta = full.replace('.zip', '.meta.json');
    if (fs.existsSync(meta)) fs.unlinkSync(meta);

    res.json({ ok: true });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Download backup ──────────────────────────────────────
router.get('/download/:filename', (req, res) => {
  const file = req.params.filename;
  if (file.includes('..') || file.includes('/') || file.includes('\\'))
    return res.status(400).send('Invalid filename');

  const full = path.join(BACKUP_DIR, file);
  if (!fs.existsSync(full)) return res.status(404).send('Not found');

  res.download(full, file);
});

// ── Get metadata for a backup ────────────────────────────
router.get('/meta/:filename', (req, res) => {
  const file = req.params.filename.replace('.zip', '.meta.json');
  const full = path.join(BACKUP_DIR, file);
  if (!fs.existsSync(full)) return res.json({ ok: true, meta: null });
  try {
    const meta = JSON.parse(fs.readFileSync(full, 'utf8'));
    res.json({ ok: true, meta });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Get backup directory setting ─────────────────────────
router.get('/config', (req, res) => {
  res.json({ ok: true, backupDir: BACKUP_DIR });
});

module.exports = router;