require('dotenv').config()
const mongoose = require('mongoose')
const items = require('./items')
const { models } = require('shared-stuff')

async function initDB () {
  await mongoose.connect(process.env.MONGODB_URI)
}

(async () => {
  await initDB()

  for (const item of items) {
    process.stdout.write(`Looking at ${item.name}: `)

    let partsPrice = 0
    for (const part of item.parts) {
      process.stdout.write(`${part.part} `)
      partsPrice += await part.getPrice()
    }

    const setPrice = await item.set.getPrice()
    await models.ScanResult.findOneAndUpdate(
      { name: item.name },
      {
        fullName: item.fullName,
        url: item.set.url,
        timestamp: new Date(),
        partsPrice,
        setPrice,
        difference: setPrice - partsPrice
      },
      { upsert: true }
    )

    console.log('✅')
  }

  await mongoose.disconnect()
})()
