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

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

  try {
    console.log('Adding missing permissions...');
    
    // Add missing permissions
    const permissions = [
      ['dashboard.widget.conversations', 'Permission for dashboard.widget.conversations', 'dashboard', 'widget.conversations'],
      ['dashboard.widget.online', 'Permission for dashboard.widget.online', 'dashboard', 'widget.online'],
      ['dashboard.widget.messages', 'Permission for dashboard.widget.messages', 'dashboard', 'widget.messages'],
      ['dashboard.widget.security', 'Permission for dashboard.widget.security', 'dashboard', 'widget.security'],
      ['security.view', 'Permission for security.view', 'security', 'view']
    ];

    for (const [name, description, resource, action] of permissions) {
      await connection.execute(
        'INSERT IGNORE INTO permissions (name, description, resource, action) VALUES (?, ?, ?, ?)',
        [name, description, resource, action]
      );
      console.log(`Added permission: ${name}`);
    }

    // Add role-permission mappings for Super Admin (role_id = 1)
    const permissionNames = permissions.map(p => p[0]);
    const [permissionIds] = await connection.execute(
      'SELECT id FROM permissions WHERE name IN (?)',
      [permissionNames]
    );

    for (const perm of permissionIds) {
      await connection.execute(
        'INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)',
        [1, perm.id]
      );
      console.log(`Added role-permission mapping for permission ID: ${perm.id}`);
    }

    console.log('✅ All missing permissions added successfully!');
  } catch (error) {
    console.error('Error:', error.message);
  } finally {
    await connection.end();
  }
}

addMissingPermissions();