/* Copy the Yamy sample data (database/yamy.db) into MongoDB. Usage: MONGODB_URI="mongodb+srv://..." node backend/seed-mongo.mjs Optional: MONGODB_DB (default "yamy"). Safe to re-run: it replaces the collections. All data is sample data. */ import { DatabaseSync } from 'node:sqlite'; import { MongoClient } from 'mongodb'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; const here = dirname(fileURLToPath(import.meta.url)); const uri = process.env.MONGODB_URI; if (!uri) { console.error('Set MONGODB_URI first (your Atlas connection string).'); process.exit(1); } const sqlite = new DatabaseSync(process.env.YAMY_DB || join(here, '..', 'database', 'yamy.db')); const client = new MongoClient(uri, { serverSelectionTimeoutMS: 10000 }); await client.connect(); const db = client.db(process.env.MONGODB_DB || 'yamy'); const tables = ['users', 'sessions', 'addresses', 'couriers', 'restaurants', 'categories', 'menu_items', 'promos', 'orders', 'order_items', 'order_events', 'reviews', 'chat_messages']; const AUTO = new Set(['users', 'addresses', 'couriers', 'restaurants', 'categories', 'menu_items', 'order_items', 'order_events', 'reviews', 'chat_messages']); for (const t of tables) { const rows = sqlite.prepare(`SELECT * FROM ${t}`).all(); await db.collection(t).drop().catch(() => {}); if (rows.length) for (let i = 0; i < rows.length; i += 1000) await db.collection(t).insertMany(rows.slice(i, i + 1000).map((r) => ({ ...r }))); if (AUTO.has(t)) { const max = rows.reduce((a, r) => Math.max(a, r.id || 0), 0); await db.collection('counters').updateOne({ _id: t }, { $set: { seq: max } }, { upsert: true }); } console.log(t.padEnd(14), rows.length); } const idx = (t, k, o) => db.collection(t).createIndex(k, o); await idx('users', { id: 1 }, { unique: true }); await idx('users', { email: 1 }, { unique: true }); await idx('sessions', { token: 1 }, { unique: true }); await idx('restaurants', { id: 1 }, { unique: true }); await idx('menu_items', { restaurant_id: 1 }); await idx('orders', { id: 1 }, { unique: true }); await idx('orders', { user_id: 1 }); await idx('order_items', { order_id: 1 }); await idx('order_events', { order_id: 1 }); await idx('reviews', { restaurant_id: 1 }); await idx('promos', { code: 1 }, { unique: true }); console.log('Done. Start the backend with MONGODB_URI set and it will use MongoDB.'); await client.close();