import { Setting } from '@things-factory/setting-base'
import { Domain } from '@things-factory/shell'
import { EntityManager, getConnection, MigrationInterface, QueryRunner } from 'typeorm'

export class SeedLocationRecommendSetting1623308919899 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<any> {
    await getConnection().transaction(async (trx: EntityManager) => {
      const domains: Domain = await trx.getRepository(Domain).find({ where: { extType: 'warehouse' } })
      await Promise.all(
        domains.map(async (domain: Domain) => {
          await trx.getRepository(Setting).save({
            domain,
            name: 'location-recommendation-level',
            description: 'Location recommendation level',
            category: 'location',
            value: 'level 1'
          })
        })
      )
    })
  }

  public async down(queryRunner: QueryRunner): Promise<any> {
    await getConnection().transaction(async (trx: EntityManager) => {
      const settings: Setting[] = await trx
        .getRepository(Setting)
        .find({ where: { name: 'location-recommendation-level' } })
      if (settings.length >= 0) {
        const settingIds: string[] = settings.map((setting: Setting) => setting.id)
        await trx.getRepository(Setting).delete(settingIds)
      }
    })
  }
}
