console.log('🚀 开始修复admin权限...');

const { sequelize } = require('../config/database');
const Role = require('../models/Role');

async function fixAdminPermissions() {
  try {
    console.log('📡 连接数据库...');
    
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    
    // 查询当前admin角色
    console.log('🔍 查询当前admin角色...');
    const adminRole = await Role.findOne({ where: { name: 'admin' } });
    
    if (adminRole) {
      console.log('📋 当前admin角色权限:', adminRole.permissions);
      
      // 更新admin角色权限，添加insurance相关权限
      console.log('🔧 更新admin角色权限...');
      const newPermissions = [
        'user:read', 'user:create', 'user:update', 'user:delete',
        'insurance:read', 'insurance:create', 'insurance:update', 'insurance:delete', 'insurance:review',
        'insurance_type:read', 'insurance_type:create', 'insurance_type:update', 'insurance_type:delete', 'insurance_type:review',
        'policy:read', 'policy:create', 'policy:update', 'policy:delete',
        'claim:read', 'claim:create', 'claim:update', 'claim:review',
        'system:read', 'system:update', 'system:admin',
        'dashboard:read', 'dashboard:update'
      ];
      
      await adminRole.update({
        permissions: JSON.stringify(newPermissions)
      });
      
      console.log('✅ admin角色权限更新成功');
      console.log('📋 新的admin权限:', newPermissions);
    } else {
      console.log('❌ 未找到admin角色');
    }
    
  } catch (error) {
    console.error('❌ 执行失败:', error.message);
    console.error('错误详情:', error);
  } finally {
    await sequelize.close();
    console.log('\n✅ 数据库连接已关闭');
  }
}

fixAdminPermissions().catch(console.error);