import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';

export class AddExplorerAndRemoveNetworkRpc1722470000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable('networks');
    if (!table) {
      return;
    }

    if (table.findColumnByName('rpc')) {
      await queryRunner.dropColumn('networks', 'rpc');
    }
    if (table.findColumnByName('api_keys')) {
      await queryRunner.dropColumn('networks', 'api_keys');
    }

    if (!table.findColumnByName('explorer')) {
      await queryRunner.addColumn(
        'networks',
        new TableColumn({
          name: 'explorer',
          type: 'varchar',
          length: '512',
          isNullable: false,
          default: "''",
        }),
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable('networks');
    if (!table) {
      return;
    }

    if (table.findColumnByName('explorer')) {
      await queryRunner.dropColumn('networks', 'explorer');
    }

    if (!table.findColumnByName('rpc')) {
      await queryRunner.addColumn(
        'networks',
        new TableColumn({ name: 'rpc', type: 'varchar', length: '255' }),
      );
    }
    if (!table.findColumnByName('api_keys')) {
      await queryRunner.addColumn(
        'networks',
        new TableColumn({ name: 'api_keys', type: 'json', isNullable: true }),
      );
    }
  }
}
