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

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

    console.log('🔧 Adding Permission Management Permissions...');
    
    const permissions = [
      {
        name: 'permission.create',
        description: 'Create new permissions',
        resource: 'permission',
        action: 'create'
      },
      {
        name: 'permission.update',
        description: 'Update existing permissions',
        resource: 'permission',
        action: 'update'
      },
      {
        name: 'permission.delete',
        description: 'Delete permissions',
        resource: 'permission',
        action: 'delete'
      },
      {
        name: 'permission.read',
        description: 'View permissions',
        resource: 'permission',
        action: 'read'
      }
    ];

    for (const perm of permissions) {
      // Check if permission already exists
      const [existingPermission] = await connection.execute(`
        SELECT id, name FROM permissions WHERE name = ?
      `, [perm.name]);
      
      if (existingPermission.length > 0) {
        console.log(`✅ ${perm.name} permission already exists`);
        const permissionId = existingPermission[0].id;
        
        // Check if it's assigned to Super Admin role (role_id = 1)
        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(`✅ ${perm.name} permission assigned to Super Admin role`);
        } else {
          console.log(`✅ ${perm.name} permission already assigned to Super Admin role`);
        }
      } else {
        // Create permission
        const [result] = await connection.execute(`
          INSERT INTO permissions (name, description, resource, action) 
          VALUES (?, ?, ?, ?)
        `, [perm.name, perm.description, perm.resource, perm.action]);
        
        const permissionId = result.insertId;
        console.log(`✅ ${perm.name} permission created with ID: ${permissionId}`);
        
        // Assign to Super Admin role (role_id = 1)
        await connection.execute(`
          INSERT INTO role_permissions (role_id, permission_id) VALUES (1, ?)
        `, [permissionId]);
        console.log(`✅ ${perm.name} permission assigned to Super Admin role`);
      }
    }
    
    // Verify the permissions
    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 IN ('permission.create', 'permission.update', 'permission.delete', 'permission.read')
      ORDER BY p.name
    `);
    
    console.log('\n📋 Permission Verification:');
    verification.forEach(row => {
      console.log(`  ✅ ${row.name} - ${row.description} (${row.role_name})`);
    });

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

addPermissionManagementPermissions();
