import { mkdirSync } from "node:fs";
import { resolve } from "node:path";
import { DatabaseSync } from "node:sqlite";

const dataDirectory = resolve(process.env.DATA_DIR ?? "data");
const backupDirectory = resolve(process.env.BACKUP_DIR ?? "backups");
const timestamp = new Date().toISOString().replaceAll(":", "-").replaceAll(".", "-");
const backupPath = resolve(backupDirectory, `game-${timestamp}.db`);
mkdirSync(backupDirectory, { recursive: true });

const database = new DatabaseSync(resolve(dataDirectory, "game.db"));
try {
  database.exec(`VACUUM INTO '${backupPath.replaceAll("'", "''")}'`);
  console.log(`SQLite backup created: ${backupPath}`);
} finally {
  database.close();
}
