#!/usr/bin/env node

//Written by Katerina Bosko

//This script replaces old meal_id generated by SQLite
// with new ObjectId generated by MongoDB in meals collections
// and inserts it into orders and ratings collection

const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017/";
// Create a new MongoClient
const client = new MongoClient(uri);

async function run() {
  try {
    // Connect the client to the server
    await client.connect();
    // Establish and verify connection
    const database = client.db("GhostKitchen");
    const orders = database.collection("orders");

    const query1 = [
      {
        $lookup: {
          from: "meals",
          localField: "meal_info.id",
          foreignField: "meal_id",
          as: "join",
        },
      },
      {
        $set: {
          "meal_info.id": "$join._id",
        },
      },
      {
        $unwind: {
          path: "$meal_info.id",
        },
      },
      {
        $project: {
          join: 0,
        },
      },
      {
        $out: "orders",
      },
    ];

    await orders.aggregate(query1).toArray();
    console.log("replaced SQLite meal_id in orders");

    const ratings = database.collection("ratings");
    const query2 = [
      {
        $lookup: {
          from: "meals",
          localField: "meal_id",
          foreignField: "meal_id",
          as: "join",
        },
      },
      {
        $set: {
          meal_id: "$join._id",
        },
      },
      {
        $unwind: {
          path: "$meal_id",
        },
      },
      {
        $project: {
          join: 0,
        },
      },
      {
        $out: "ratings",
      },
    ];

    await ratings.aggregate(query2).toArray();

    console.log("replaced SQLite meal_id in ratings");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);
