import { MigrationInterface, QueryRunner } from 'typeorm';

const BACKFILLED_KEYS = [
  'invite_min_role',
  'member_manage_min_role',
  'penalty_manage_min_role',
  'public_access_manage_min_role',
] as const;

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    for (const key of BACKFILLED_KEYS) {
      await queryRunner.query(
        `INSERT INTO "team_setting" ("teamId", "key", "value")
         SELECT "id", '${key}', '3' FROM "team"
         WHERE NOT EXISTS (
           SELECT 1 FROM "team_setting" ts
           WHERE ts."teamId" = "team"."id" AND ts."key" = '${key}'
         )`,
      );
    }

    await queryRunner.query(
      `INSERT INTO "team_setting" ("teamId", "key", "value")
       SELECT "teamId", 'transaction_reverse_min_role', "value" FROM "team_setting"
       WHERE "key" = 'transaction_create_min_role'
         AND "teamId" NOT IN (
           SELECT "teamId" FROM "team_setting" WHERE "key" = 'transaction_reverse_min_role'
         )`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DELETE FROM "team_setting" WHERE "key" IN (
        'transaction_reverse_min_role',
        'invite_min_role',
        'member_manage_min_role',
        'penalty_manage_min_role',
        'public_access_manage_min_role'
      )`,
    );
  }
}
