import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const BACKEND_DIR = path.join(__dirname, '..');
const BACKUPS_DIR = path.join(BACKEND_DIR, 'backups');

const DB_FILES = [
  'orders.json',
  'users.json',
  'creators.json',
  'withdrawals.json',
  'config.json'
];

/**
 * Crea una instantánea completa de la base de datos JSON y la guarda en backend/backups/.
 */
export function createBackup() {
  if (!fs.existsSync(BACKUPS_DIR)) {
    fs.mkdirSync(BACKUPS_DIR, { recursive: true });
  }

  const now = new Date();
  const dateStr = now.toISOString().slice(0, 10); // YYYY-MM-DD
  const backupFilename = `backup-${dateStr}.json`;
  const backupPath = path.join(BACKUPS_DIR, backupFilename);

  const snapshot = {
    timestamp: now.toISOString(),
    files: {}
  };

  for (const filename of DB_FILES) {
    const filePath = path.join(BACKEND_DIR, filename);
    if (fs.existsSync(filePath)) {
      try {
        const raw = fs.readFileSync(filePath, 'utf-8');
        snapshot.files[filename] = JSON.parse(raw);
      } catch (err) {
        console.error(`[BackupManager] Error leyendo ${filename}:`, err.message);
      }
    }
  }

  try {
    fs.writeFileSync(backupPath, JSON.stringify(snapshot, null, 2), 'utf-8');
    console.log(`[BackupManager] ✅ Respaldo guardado con éxito: ${backupFilename}`);
    pruneOldBackups(14); // Mantener últimos 14 días
    return { success: true, file: backupFilename, path: backupPath, timestamp: snapshot.timestamp };
  } catch (err) {
    console.error('[BackupManager] Error escribiendo respaldo:', err.message);
    return { success: false, error: err.message };
  }
}

/**
 * Limpia automáticamente los respaldos que tengan más de maxDays días.
 */
function pruneOldBackups(maxDays = 14) {
  try {
    if (!fs.existsSync(BACKUPS_DIR)) return;
    const files = fs.readdirSync(BACKUPS_DIR).filter(f => f.startsWith('backup-') && f.endsWith('.json'));
    const maxAgeMs = maxDays * 24 * 60 * 60 * 1000;
    const now = Date.now();

    for (const f of files) {
      const fullPath = path.join(BACKUPS_DIR, f);
      const stat = fs.statSync(fullPath);
      if (now - stat.mtimeMs > maxAgeMs) {
        fs.unlinkSync(fullPath);
        console.log(`[BackupManager] 🗑️ Respaldo antiguo eliminado: ${f}`);
      }
    }
  } catch (err) {
    console.error('[BackupManager] Error limpiando respaldos antiguos:', err.message);
  }
}

/**
 * Inicializa el temporizador de respaldo automático cada 24 horas.
 */
export function initAutoBackup() {
  // Crear respaldo inicial al arrancar el servidor
  try {
    createBackup();
  } catch (e) {
    console.error('[BackupManager] Error en respaldo inicial:', e.message);
  }

  // Intervalo de 24 horas (24 * 60 * 60 * 1000 ms)
  const INTERVAL_24H = 24 * 60 * 60 * 1000;
  setInterval(() => {
    try {
      createBackup();
    } catch (e) {
      console.error('[BackupManager] Error en respaldo programado:', e.message);
    }
  }, INTERVAL_24H).unref(); // unref para no impedir que Node se cierre limpiamente
}
