import { MigrationInterface, QueryRunner } from 'typeorm';

export class RouteStatusAndSegmentKm1830000000001 implements MigrationInterface {
  name = 'RouteStatusAndSegmentKm1830000000001';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.routes
      ADD COLUMN IF NOT EXISTS status varchar(32) NOT NULL DEFAULT 'AVAILABLE'
    `);

    await queryRunner.query(`
      UPDATE freight.routes
      SET status = CASE WHEN is_active = true THEN 'AVAILABLE' ELSE 'STOP_WORKING' END
    `);

    await queryRunner.query(`
      DROP INDEX IF EXISTS freight."IDX_routes_name"
    `);
    await queryRunner.query(`
      ALTER TABLE freight.routes DROP COLUMN IF EXISTS name
    `);
    await queryRunner.query(`
      ALTER TABLE freight.routes DROP COLUMN IF EXISTS is_active
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_routes_status" ON freight.routes (status)
    `);

    await queryRunner.query(`
      ALTER TABLE freight.route_milestones
      ADD COLUMN IF NOT EXISTS distance_km numeric(10,2)
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.route_milestones DROP COLUMN IF EXISTS distance_km
    `);

    await queryRunner.query(`
      ALTER TABLE freight.routes
      ADD COLUMN IF NOT EXISTS name varchar(120)
    `);
    await queryRunner.query(`
      UPDATE freight.routes SET name = id::text WHERE name IS NULL
    `);
    await queryRunner.query(`
      ALTER TABLE freight.routes ALTER COLUMN name SET NOT NULL
    `);

    await queryRunner.query(`
      ALTER TABLE freight.routes
      ADD COLUMN IF NOT EXISTS is_active boolean NOT NULL DEFAULT true
    `);
    await queryRunner.query(`
      UPDATE freight.routes
      SET is_active = CASE WHEN status = 'AVAILABLE' THEN true ELSE false END
    `);

    await queryRunner.query(`
      ALTER TABLE freight.routes DROP COLUMN IF EXISTS status
    `);
    await queryRunner.query(`
      DROP INDEX IF EXISTS freight."IDX_routes_status"
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "IDX_routes_name" ON freight.routes (name)
    `);
  }
}
