import { readdirSync, readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { createDatabase } from "../server/database.ts";
const db = createDatabase();
db.exec(
  "CREATE TABLE IF NOT EXISTS _migrations(name TEXT PRIMARY KEY, checksum TEXT NOT NULL, applied_at TEXT NOT NULL)",
);
for (const name of readdirSync("migrations")
  .filter((n) => n.endsWith(".sql"))
  .sort()) {
  const source = readFileSync(`migrations/${name}`, "utf8"),
    checksum = createHash("sha256").update(source).digest("hex");
  const applied = db
    .prepare("SELECT checksum FROM _migrations WHERE name=?")
    .get(name);
  if (applied) {
    if (applied.checksum !== checksum)
      throw new Error(`Migration changed: ${name}`);
    continue;
  }
  db.exec("BEGIN IMMEDIATE");
  try {
    db.exec(source);
    db.prepare("INSERT INTO _migrations VALUES (?,?,?)").run(
      name,
      checksum,
      new Date().toISOString(),
    );
    db.exec("COMMIT");
    console.log(`Applied ${name}`);
  } catch (error) {
    db.exec("ROLLBACK");
    throw error;
  }
}
db.close();
