#!/usr/bin/env node
import initSqlJs from 'sql.js';
import fs from 'fs';

const DB_PATH = 'data/recipes.db';

async function updateDatabase() {
  const SQL = await initSqlJs();
  const dbBuffer = fs.readFileSync(DB_PATH);
  const db = new SQL.Database(dbBuffer);

  // Update all image_url paths: 'images/...' → '/images/...'
  const result = db.run(`
    UPDATE recipes 
    SET image_url = '/' || image_url 
    WHERE image_url LIKE 'images/%' AND image_url NOT LIKE '/%'
  `);

  console.log(`✓ Updated ${result} records`);

  // Verify
  const check = db.exec(`SELECT id, title, image_url FROM recipes WHERE image_url LIKE '/images/%' LIMIT 5`);
  if (check.length > 0) {
    console.log('\n✓ Sample updated records:');
    check[0].values.forEach(([id, title, imageUrl]) => {
      console.log(`  ${id}: ${title} → ${imageUrl}`);
    });
  }

  // Save
  const data = db.export();
  fs.writeFileSync(DB_PATH, data);
  db.close();

  console.log('\n✓ Database saved');
}

updateDatabase().catch(console.error);
