const mysql = require('mysql2/promise');
require('dotenv').config();

/**
 * 修复admin用户权限脚本
 * 添加缺失的supervision_tasks:read和installation_tasks:read权限
 */

async function fixAdminPermissions() {
  let connection;
  
  try {
    // 创建数据库连接
    connection = await mysql.createConnection({
      host: process.env.DB_HOST || '129.211.213.226',
      port: process.env.DB_PORT || 9527,
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || 'aiotAiot123!',
      database: process.env.DB_NAME || 'insurance_data'
    });
    
    console.log('✅ 数据库连接成功');
    
    // 查询当前admin角色的权限
    const [adminRole] = await connection.query(
      'SELECT id, name, permissions FROM roles WHERE name = ?',
      ['admin']
    );
    
    if (adminRole.length === 0) {
      console.log('❌ 未找到admin角色');
      return;
    }
    
    console.log('📋 当前admin角色权限:', adminRole[0].permissions);
    
    // 解析当前权限
    let currentPermissions;
    try {
      currentPermissions = JSON.parse(adminRole[0].permissions);
    } catch (error) {
      console.log('⚠️  权限格式错误，重新设置为完整权限列表');
      currentPermissions = [];
    }
    
    // 定义完整的权限列表
    const fullPermissions = [
      "user:read", "user:create", "user:update", "user:delete",
      "insurance:read", "insurance:create", "insurance:update", "insurance:delete", "insurance:review",
      "policy:read", "policy:create", "policy:update", "policy:delete",
      "livestock_policy:read", "livestock_policy:create", "livestock_policy:update", "livestock_policy:delete",
      "claim:read", "claim:create", "claim:update", "claim:review",
      "supervision_tasks:read", "supervision_tasks:create", "supervision_tasks:update", "supervision_tasks:delete",
      "installation_tasks:read", "installation_tasks:create", "installation_tasks:update", "installation_tasks:delete",
      "system:read", "system:update", "system:admin",
      "data:read", "data:create", "data:update", "data:delete"
    ];
    
    // 更新admin角色权限
    await connection.query(
      'UPDATE roles SET permissions = ? WHERE name = ?',
      [JSON.stringify(fullPermissions), 'admin']
    );
    
    console.log('✅ admin角色权限已更新');
    console.log('📋 新的权限列表:', JSON.stringify(fullPermissions, null, 2));
    
    // 查询admin用户并更新其权限缓存
    const [adminUsers] = await connection.query(
      'SELECT id, username FROM users WHERE role_id = ?',
      [adminRole[0].id]
    );
    
    console.log(`✅ 找到 ${adminUsers.length} 个admin用户，权限已生效`);
    
    // 验证权限更新
    const [updatedRole] = await connection.query(
      'SELECT permissions FROM roles WHERE name = ?',
      ['admin']
    );
    
    let updatedPermissions;
    try {
      updatedPermissions = JSON.parse(updatedRole[0].permissions);
    } catch (error) {
      console.log('⚠️  验证时权限格式错误:', updatedRole[0].permissions);
      updatedPermissions = fullPermissions; // 使用我们刚设置的权限
    }
    
    const hasSupervisionRead = updatedPermissions.includes('supervision_tasks:read');
    const hasInstallationRead = updatedPermissions.includes('installation_tasks:read');
    
    console.log('🔍 权限验证:');
    console.log(`  - supervision_tasks:read: ${hasSupervisionRead ? '✅' : '❌'}`);
    console.log(`  - installation_tasks:read: ${hasInstallationRead ? '✅' : '❌'}`);
    
    if (hasSupervisionRead && hasInstallationRead) {
      console.log('🎉 权限修复成功！');
    } else {
      console.log('❌ 权限修复失败，请检查数据库');
    }
    
  } catch (error) {
    console.error('❌ 权限修复失败:', error.message);
    throw error;
  } finally {
    // 关闭数据库连接
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 执行脚本
fixAdminPermissions()
  .then(() => {
    console.log('✨ 权限修复任务已完成');
    process.exit(0);
  })
  .catch(() => {
    console.error('❌ 权限修复任务失败');
    process.exit(1);
  });