const { pool } = require('../config/database')

// Permission-based authorization middleware
const requirePermission = (permission) => {
  return async (req, res, next) => {
    try {
      const userId = req.user?.id

      if (!userId) {
        return res.status(401).json({
          status: 'error',
          message: 'Authentication required'
        })
      }

      // Get user's role and permissions
      const [userRole] = await pool.execute(
        `SELECT r.name as role_name, r.level as role_level
         FROM users u
         JOIN roles r ON u.role_id = r.id
         WHERE u.id = ?`,
        [userId]
      )

      if (userRole.length === 0) {
        return res.status(403).json({
          status: 'error',
          message: 'User role not found'
        })
      }

      const role = userRole[0]

      // Super Admin has all permissions
      if (role.role_level >= 100) {
        return next()
      }

      // Check if user has the specific permission
      const [permissions] = await pool.execute(
        `SELECT p.name
         FROM permissions p
         JOIN role_permissions rp ON p.id = rp.permission_id
         JOIN roles r ON rp.role_id = r.id
         JOIN users u ON u.role_id = r.id
         WHERE u.id = ? AND p.name = ?`,
        [userId, permission]
      )

      if (permissions.length === 0) {
        return res.status(403).json({
          status: 'error',
          message: `Permission '${permission}' required`
        })
      }

      next()
    } catch (error) {
      console.error('Permission check error:', error)
      res.status(500).json({
        status: 'error',
        message: 'Internal server error'
      })
    }
  }
}

// Multiple permissions check (user needs ANY of the permissions)
const requireAnyPermission = (permissions) => {
  return async (req, res, next) => {
    try {
      const userId = req.user?.id

      if (!userId) {
        return res.status(401).json({
          status: 'error',
          message: 'Authentication required'
        })
      }

      // Get user's role
      const [userRole] = await pool.execute(
        `SELECT r.name as role_name, r.level as role_level
         FROM users u
         JOIN roles r ON u.role_id = r.id
         WHERE u.id = ?`,
        [userId]
      )

      if (userRole.length === 0) {
        return res.status(403).json({
          status: 'error',
          message: 'User role not found'
        })
      }

      const role = userRole[0]

      // Super Admin has all permissions
      if (role.role_level >= 100) {
        return next()
      }

      // Check if user has ANY of the required permissions
      const permissionPlaceholders = permissions.map(() => '?').join(',')
      const [userPermissions] = await pool.execute(
        `SELECT p.name
         FROM permissions p
         JOIN role_permissions rp ON p.id = rp.permission_id
         JOIN roles r ON rp.role_id = r.id
         JOIN users u ON u.role_id = r.id
         WHERE u.id = ? AND p.name IN (${permissionPlaceholders})`,
        [userId, ...permissions]
      )

      if (userPermissions.length === 0) {
        return res.status(403).json({
          status: 'error',
          message: `One of these permissions required: ${permissions.join(', ')}`
        })
      }

      next()
    } catch (error) {
      console.error('Permission check error:', error)
      res.status(500).json({
        status: 'error',
        message: 'Internal server error'
      })
    }
  }
}

// Role level check (user needs minimum role level)
const requireRoleLevel = (minLevel) => {
  return async (req, res, next) => {
    try {
      const userId = req.user?.id

      if (!userId) {
        return res.status(401).json({
          status: 'error',
          message: 'Authentication required'
        })
      }

      // Get user's role level
      const [userRole] = await pool.execute(
        `SELECT r.level as role_level
         FROM users u
         JOIN roles r ON u.role_id = r.id
         WHERE u.id = ?`,
        [userId]
      )

      if (userRole.length === 0) {
        return res.status(403).json({
          status: 'error',
          message: 'User role not found'
        })
      }

      const roleLevel = userRole[0].role_level

      if (roleLevel < minLevel) {
        return res.status(403).json({
          status: 'error',
          message: `Minimum role level ${minLevel} required`
        })
      }

      next()
    } catch (error) {
      console.error('Role level check error:', error)
      res.status(500).json({
        status: 'error',
        message: 'Internal server error'
      })
    }
  }
}

module.exports = {
  requirePermission,
  requireAnyPermission,
  requireRoleLevel
}
