import type { Database } from 'sql.js';

function hasColumn(db: Database, tableName: string, columnName: string): boolean {
  const pragma = db.exec(`PRAGMA table_info(${tableName})`);
  if (!pragma.length) return false;
  return pragma[0].values.some((row) => row[1] === columnName);
}

/**
 * Idempotent runtime migrations for existing DB files.
 */
export function applyRuntimeMigrations(db: Database): void {
  const hasRecipesTable = db.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='recipes'");
  if (!hasRecipesTable.length || !hasRecipesTable[0].values.length) {
    return;
  }

  if (!hasColumn(db, 'recipes', 'image_url')) {
    db.exec('ALTER TABLE recipes ADD COLUMN image_url TEXT');
  }

  // 2026-03-28: User metadata fields for CopyMeThat import
  if (!hasColumn(db, 'recipes', 'made')) {
    db.exec('ALTER TABLE recipes ADD COLUMN made INTEGER DEFAULT 0');
  }
  if (!hasColumn(db, 'recipes', 'rating')) {
    db.exec('ALTER TABLE recipes ADD COLUMN rating INTEGER');
  }
  if (!hasColumn(db, 'recipes', 'notes')) {
    db.exec('ALTER TABLE recipes ADD COLUMN notes TEXT');
  }
}
