import initSqlJs from 'sql.js';
import fs from 'fs';
import path from 'path';
import { applyRuntimeMigrations } from './schemaMigrations.js';

const DATA_DIR = path.resolve(process.cwd(), 'data');
const DB_PATH = path.join(DATA_DIR, 'recipes.db');
const SCHEMA_PATH = path.resolve(process.cwd(), 'src/backend/db/schema.sql');

async function ensureDataDir() {
  if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
    console.log(`Created data directory at ${DATA_DIR}`);
  }
}

async function applyMigrations() {
  await ensureDataDir();

  const schema = fs.readFileSync(SCHEMA_PATH, 'utf8');
  const SQL = await initSqlJs();
  const db = fs.existsSync(DB_PATH)
    ? new SQL.Database(fs.readFileSync(DB_PATH))
    : new SQL.Database();

  const hasRecipesTable = db.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='recipes'");
  if (!hasRecipesTable.length || !hasRecipesTable[0].values.length) {
    db.exec(schema);
  }

  applyRuntimeMigrations(db);

  const data = db.export();
  fs.writeFileSync(DB_PATH, Buffer.from(data));
  db.close();
  console.log(`Database migrated: ${DB_PATH}`);
}

if (import.meta.url === `file://${process.argv[1]}`) {
  applyMigrations();
}

export { applyMigrations };
