import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // 插入默认角色数据，使用 ON CONFLICT 确保幂等性
    await queryRunner.query(`
      INSERT INTO role (tenant_id, name, description, permissions)
      VALUES
      (1, 'super-admin', '超级管理员', 'advertisement:manage'),
      (1, 'admin', '普通管理员', '')
      ON CONFLICT (tenant_id, name) DO UPDATE
      SET permissions =
        CASE
          WHEN EXCLUDED.name = 'super-admin' THEN
            -- 超级管理员：确保有 advertisement:manage 权限，保留其他现有权限
            CASE
              WHEN role.permissions = '' THEN 'advertisement:manage'
              ELSE CONCAT(role.permissions, ',advertisement:manage')
            END
          WHEN EXCLUDED.name = 'admin' THEN
            -- 普通管理员：确保没有 advertisement:manage 权限，保留其他现有权限
            REPLACE(role.permissions, 'advertisement:manage', '')
        END,
      description = EXCLUDED.description;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 回滚：删除插入的默认角色数据（仅删除租户ID为1的默认角色）
    await queryRunner.query(`
      DELETE FROM role
      WHERE tenant_id = 1 AND name IN ('super-admin', 'admin');
    `);
  }
}