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

const sourcePath = resolve('data/game.db')
const backupDirectory = resolve('backups')
const timestamp = new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-')
const backupPath = resolve(backupDirectory, `game-${timestamp}.db`)

mkdirSync(backupDirectory, { recursive: true })

const database = new DatabaseSync(sourcePath)

try {
  const escapedPath = backupPath.replaceAll("'", "''")
  database.exec(`VACUUM INTO '${escapedPath}'`)
  console.log(`SQLite backup created: ${backupPath}`)
} finally {
  database.close()
}
