const fs = require('fs')
const path = require('path')
const Database = require('better-sqlite3')

const dbPath = process.env.DATABASE_PATH || path.join(process.cwd(), 'skillmate.dev.encrypted.db')
const db = new Database(dbPath)

function ensureSchemaTable() {
  db.exec(`CREATE TABLE IF NOT EXISTS schema_version (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`)
}

function getApplied() {
  try {
    const rows = db.prepare('SELECT id FROM schema_version').all()
    return new Set(rows.map(r => r.id))
  } catch {
    return new Set()
  }
}

function applyMigration(file) {
  const migration = require(file)
  const id = path.basename(file)
  const tx = db.transaction(() => {
    migration.up(db)
    db.prepare('INSERT INTO schema_version (id, applied_at) VALUES (?, ?)').run(id, new Date().toISOString())
  })
  tx()
  console.log('Applied migration:', id)
}

function main() {
  ensureSchemaTable()
  const applied = getApplied()
  const dir = path.join(__dirname, 'migrations')
  if (!fs.existsSync(dir)) {
    console.log('No migrations directory found, skipping.')
    process.exit(0)
  }
  const files = fs.readdirSync(dir)
    .filter(f => f.endsWith('.js'))
    .sort()
    .map(f => path.join(dir, f))
  for (const file of files) {
    const id = path.basename(file)
    if (!applied.has(id)) {
      applyMigration(file)
    }
  }
  console.log('Migrations complete.')
}

main()

