text: import Registration from '@apps/events/models/registration'
  import TicketType from '@apps/events/models/ticket_type'
  import Product from '@apps/stores/models/product'
  import Order from '@apps/stores/models/order'
  
  const AddLineItemKeys = {
  
    databaseName: 'maha',
  
    up: async (knex) => {
  
      const req = { trx: knex }
  
      await knex.schema.table('finance_line_items', (table) => {
        table.integer('ticket_type_id').unsigned()
        table.foreign('ticket_type_id').references('events_ticket_types.id')
        table.integer('variant_id').unsigned()
        table.foreign('variant_id').references('stores_variants.id')
      })
  
      const orders = Order.fetchAll({
        withRelated: ['store','invoice.line_items'],
        transacting: req.trx
      })
  
      await Promise.mapSeries(orders, async (order) => {
        await Promise.mapSeries(order.related('invoice').related('line_items'), async (item) => {
          const store = order.related('store')
          const title = item.get('description').replace(`${store.get('title')}: `, '')
          const product = await Product.query(qb => {
            qb.where('store_id', store.get('id'))
            qb.where('title', title)
          }).fetch({
            withRelated: ['variants'],
            transacting: req.trx
          })
          if(!product || product.related('variants').length === 0) return
          const variant = product.related('variants').toArray()[0]
          await item.save({
            variant_id: variant.get('id')
          }, {
            transacting: req.trx
          })
        })
      })
  
      const registrations = Registration.fetchAll({
        withRelated: ['event','invoice.line_items'],
        transacting: req.trx
      })
  
      await Promise.mapSeries(registrations, async (registration) => {
        await Promise.mapSeries(registration.related('invoice').related('line_items'), async (item) => {
          const event = registration.related('event')
          const name = item.get('description').replace(`${event.get('title')}: `, '')
          const ticket_type = await TicketType.query(qb => {
            qb.where('event_id', event.get('id'))
            qb.where('name', name)
          }).fetch({
            transacting: req.trx
          })
          if(!ticket_type) return
          await item.save({
            ticket_type_id: ticket_type.get('id')
          }, {
            transacting: req.trx
          })
        })
      })
  
    },
  
    down: async (knex) => {
    }
  
  }
  
  export default AddLineItemKeys
  