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

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

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

    const hasForeignKey = table.foreignKeys.some((fk) =>
      fk.columnNames.includes('network_id'),
    );
    if (!hasForeignKey) {
      await queryRunner.createForeignKey(
        'addresses',
        new TableForeignKey({
          columnNames: ['network_id'],
          referencedColumnNames: ['id'],
          referencedTableName: 'networks',
          onDelete: 'SET NULL',
        }),
      );
    }
  }

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

    const foreignKey = table.foreignKeys.find((fk) =>
      fk.columnNames.includes('network_id'),
    );
    if (foreignKey) {
      await queryRunner.dropForeignKey('addresses', foreignKey);
    }

    if (table.findColumnByName('network_id')) {
      await queryRunner.dropColumn('addresses', 'network_id');
    }
  }
}
