const mysql = require('mysql2/promise');

async function addDashboardReadPermission() {
  try {
    const connection = await mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '',
      database: 'cms_db'
    });

    console.log('🔧 Adding dashboard.read permission...');
    
    // Check if dashboard.read permission already exists
    const [existingPermission] = await connection.execute(`
      SELECT id, name FROM permissions WHERE name = 'dashboard.read'
    `);
    
    if (existingPermission.length > 0) {
      console.log('✅ dashboard.read permission already exists');
      const permissionId = existingPermission[0].id;
      
      // Check if it's assigned to Navy_admin role (role_id = 6)
      const [rolePermission] = await connection.execute(`
        SELECT rp.id FROM role_permissions rp 
        WHERE rp.role_id = 6 AND rp.permission_id = ?
      `, [permissionId]);
      
      if (rolePermission.length > 0) {
        console.log('✅ dashboard.read permission already assigned to Navy_admin role');
      } else {
        // Assign to Navy_admin role
        await connection.execute(`
          INSERT INTO role_permissions (role_id, permission_id) VALUES (6, ?)
        `, [permissionId]);
        console.log('✅ dashboard.read permission assigned to Navy_admin role');
      }
    } else {
      // Create dashboard.read permission
      const [result] = await connection.execute(`
        INSERT INTO permissions (name, description, resource, action) 
        VALUES ('dashboard.read', 'Read dashboard data and statistics', 'dashboard', 'read')
      `);
      
      const permissionId = result.insertId;
      console.log('✅ dashboard.read permission created with ID:', permissionId);
      
      // Assign to Navy_admin role (role_id = 6)
      await connection.execute(`
        INSERT INTO role_permissions (role_id, permission_id) VALUES (6, ?)
      `, [permissionId]);
      console.log('✅ dashboard.read permission assigned to Navy_admin role');
    }
    
    // Also assign to Super Admin role (role_id = 1) if not already assigned
    const [superAdminPermission] = await connection.execute(`
      SELECT id FROM permissions WHERE name = 'dashboard.read'
    `);
    
    if (superAdminPermission.length > 0) {
      const permissionId = superAdminPermission[0].id;
      
      const [superAdminRolePermission] = await connection.execute(`
        SELECT rp.id FROM role_permissions rp 
        WHERE rp.role_id = 1 AND rp.permission_id = ?
      `, [permissionId]);
      
      if (superAdminRolePermission.length === 0) {
        await connection.execute(`
          INSERT INTO role_permissions (role_id, permission_id) VALUES (1, ?)
        `, [permissionId]);
        console.log('✅ dashboard.read permission assigned to Super Admin role');
      } else {
        console.log('✅ dashboard.read permission already assigned to Super Admin role');
      }
    }
    
    // Verify the permission
    const [verification] = await connection.execute(`
      SELECT p.name, p.description, r.name as role_name
      FROM permissions p
      JOIN role_permissions rp ON p.id = rp.permission_id
      JOIN roles r ON rp.role_id = r.id
      WHERE p.name = 'dashboard.read'
    `);
    
    console.log('\n📋 Permission Verification:');
    verification.forEach(row => {
      console.log(`  ✅ ${row.name} - ${row.description} (${row.role_name})`);
    });

    await connection.end();
    console.log('\n🎉 Dashboard.read permission setup completed!');
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

addDashboardReadPermission();
