import 'dotenv/config';
import { db, initDB } from './src/core/db.js';

await initDB();

console.log('🔧 Auto-generating SKU for existing products...\n');

// Get products without SKU
const products = db.prepare('SELECT id, name FROM products WHERE sku IS NULL').all();

if (!products.length) {
  console.log('✅ All products already have SKU');
  process.exit(0);
}

console.log(`Found ${products.length} products without SKU:\n`);

for (const p of products) {
  // Generate random 4-char alphanumeric
  const random = Math.random().toString(36).substring(2, 6).toLowerCase();
  const sku = `product_${random}`;

  // Check uniqueness (very unlikely to collide, but just in case)
  const existing = db.prepare('SELECT id FROM products WHERE sku = ?').get(sku);
  if (existing) {
    console.log(`⚠️  SKU collision for ${sku}, regenerating...`);
    continue; // Will retry on next run
  }

  // Update product
  db.prepare('UPDATE products SET sku = ? WHERE id = ?').run(sku, p.id);
  console.log(`✅ #${p.id} "${p.name}" → ${sku}`);
}

console.log('\n🎉 Done! All products now have SKU.');
console.log('\nℹ️  You can edit SKU in dashboard to use custom prefix (d3_, d1_, spotify_, etc)');

process.exit(0);
