import { MigrationInterface, QueryRunner } from 'typeorm'
import { getRepository } from 'typeorm'
import { Domain } from '@things-factory/shell'
import { Group } from '@things-factory/board-service'

const SEED_GROUP = [
  {
    name: 'LABEL',
    description: 'LABEL'
  },
  {
    name: 'WAREHOUSE',
    description: 'WAREHOUSE'
  },
  {
    name: 'LOGISTICS',
    description: 'LOGISTICS'
  }
]

export class SeedGroup1558006505982 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<any> {
    const repository = getRepository(Group)
    const domainRepository = getRepository(Domain)
    const domain = await domainRepository.findOne({ subdomain: 'system' })

    return await Promise.all(
      SEED_GROUP.map(async group => {
        await repository.save({
          ...group,
          domain
        })
      })
    )
  }

  public async down(queryRunner: QueryRunner): Promise<any> {
    const repository = getRepository(Group)

    return await Promise.all(
      SEED_GROUP.reverse().map(async group => {
        let record = await repository.findOne({ name: group.name })
        await repository.remove(record)
      })
    )
  }
}
