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

/**
 * shipping_lines was created without a unique index on code; seeder upserts require it.
 */
export class AddShippingLinesCodeUniqueIndex1749800000000 implements MigrationInterface {
  name = 'AddShippingLinesCodeUniqueIndex1749800000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    const existing = await queryRunner.query(
      `SELECT 1 FROM pg_indexes WHERE schemaname = 'freight' AND tablename = 'shipping_lines' AND indexdef ILIKE '%UNIQUE%code%' LIMIT 1`,
    );
    if (existing.length === 0) {
      await queryRunner.createIndex(
        'freight.shipping_lines',
        new TableIndex({
          name: 'UQ_shipping_lines_code',
          columnNames: ['code'],
          isUnique: true,
        }),
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropIndex('freight.shipping_lines', 'UQ_shipping_lines_code');
  }
}
