// Get pool from global or create a new one if not available
let pool;
if (typeof global.pool !== 'undefined') {
  pool = global.pool;
} else {
  // If global pool is not available, create a new connection
  const { Pool } = require('pg');
  pool = new Pool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    port: process.env.DB_PORT,
  });
  console.log('Created new database pool in permissions.js');
}

/**
 * Check if a user has a specific permission
 * @param {number} userId - The user ID to check
 * @param {string} permissionCode - The permission code to check
 * @returns {Promise<boolean>} - Whether the user has the permission
 */
async function checkPermission(userId, permissionCode) {
  try {
    // First check if the user is an admin
    const adminResult = await pool.query(
      'SELECT is_admin FROM users WHERE id = $1',
      [userId]
    );
    
    // If user is admin, automatically grant permission
    if (adminResult.rows.length > 0 && adminResult.rows[0].is_admin) {
      return true;
    }
    
    // Otherwise check for specific permission
    const result = await pool.query(
      `SELECT COUNT(*) AS has_permission
       FROM user_permissions up
       JOIN permissions p ON up.permission_id = p.id
       WHERE up.user_id = $1 AND p.code = $2`,
      [userId, permissionCode]
    );
    
    return result.rows[0].has_permission > 0;
  } catch (error) {
    console.error('Error checking permission:', error);
    return false;
  }
}

/**
 * Middleware to require a specific permission
 * @param {string} permissionCode - The permission code required
 * @returns {Function} - Express middleware function
 */
function requirePermission(permissionCode) {
  return async (req, res, next) => {
    try {
      // Check if user is authenticated
      if (!req.user || !req.user.id) {
        return res.status(401).json({ error: 'Authentication required' });
      }
      
      const hasPermission = await checkPermission(req.user.id, permissionCode);
      
      if (!hasPermission) {
        return res.status(403).json({ 
          error: 'Insufficient permissions',
          requiredPermission: permissionCode
        });
      }
      
      next();
    } catch (error) {
      console.error('Permission middleware error:', error);
      res.status(500).json({ error: 'Server error checking permissions' });
    }
  };
}

/**
 * Get all permissions for a user
 * @param {number} userId - The user ID
 * @returns {Promise<string[]>} - Array of permission codes
 */
async function getUserPermissions(userId) {
  try {
    // Check if user is admin
    const adminResult = await pool.query(
      'SELECT is_admin FROM users WHERE id = $1',
      [userId]
    );
    
    if (adminResult.rows.length === 0) {
      return [];
    }
    
    const isAdmin = adminResult.rows[0].is_admin;
    
    if (isAdmin) {
      // Admin gets all permissions
      const allPermissions = await pool.query('SELECT code FROM permissions');
      return allPermissions.rows.map(p => p.code);
    } else {
      // Get assigned permissions
      const permissions = await pool.query(
        `SELECT p.code
         FROM permissions p
         JOIN user_permissions up ON p.id = up.permission_id
         WHERE up.user_id = $1`,
        [userId]
      );
      
      return permissions.rows.map(p => p.code);
    }
  } catch (error) {
    console.error('Error getting user permissions:', error);
    return [];
  }
}

module.exports = {
  checkPermission,
  requirePermission,
  getUserPermissions
}; 