import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`ALTER TABLE "rooms" ADD COLUMN "hasPassword" INTEGER NOT NULL DEFAULT 0`);
    await queryRunner.query(`ALTER TABLE "rooms" ADD COLUMN "sourceId" TEXT`);
    await queryRunner.query(`ALTER TABLE "rooms" ADD COLUMN "sourceName" TEXT`);
    await queryRunner.query(`ALTER TABLE "rooms" ADD COLUMN "sourceUrl" TEXT`);
    await queryRunner.query(`
      UPDATE "rooms"
      SET "hasPassword" = CASE
        WHEN "password" IS NOT NULL AND TRIM("password") <> '' THEN 1
        ELSE 0
      END
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`ALTER TABLE "rooms" DROP COLUMN "sourceUrl"`);
    await queryRunner.query(`ALTER TABLE "rooms" DROP COLUMN "sourceName"`);
    await queryRunner.query(`ALTER TABLE "rooms" DROP COLUMN "sourceId"`);
    await queryRunner.query(`ALTER TABLE "rooms" DROP COLUMN "hasPassword"`);
  }
}
