import { pool } from "../config/db.js";
import { writeAuditLog } from "../utils/audit.js";

const BACKUP_TABLES = [
  "configuracion",
  "customers",
  "services",
  "orders",
  "order_items",
  "payments",
  "payment_methods",
  "products",
  "cash_register_sessions",
  "cash_register_movements",
  "cash_register_shifts",
  "loyalty_tiers",
  "loyalty_rewards",
  "loyalty_points",
  "loyalty_redemptions",
  "users",
  "audit_logs"
];

async function tableExists(tableName) {
  const [rows] = await pool.query("SHOW TABLES LIKE ?", [tableName]);
  return rows.length > 0;
}

function sanitizeRows(tableName, rows) {
  if (tableName !== "users") return rows;
  return rows.map(({ password, reset_token, reset_token_expires, ...user }) => user);
}

export async function downloadBackup(req, res, next) {
  try {
    const tables = {};

    for (const tableName of BACKUP_TABLES) {
      if (!(await tableExists(tableName))) continue;
      const [rows] = await pool.query(`SELECT * FROM \`${tableName}\``);
      tables[tableName] = sanitizeRows(tableName, rows);
    }

    await writeAuditLog(req, {
      action: "backup",
      entity: "backup",
      details: { tables: Object.keys(tables) }
    });

    const stamp = new Date().toISOString().replace(/[:.]/g, "-");
    res.setHeader("Content-Type", "application/json; charset=utf-8");
    res.setHeader("Content-Disposition", `attachment; filename="laundry_backup_${stamp}.json"`);
    res.json({
      generatedAt: new Date().toISOString(),
      generatedBy: req.user?.username || null,
      app: "laundry_full_solution",
      tables
    });
  } catch (err) {
    next(err);
  }
}
