// Simple test without mocha framework
const { expect } = require('chai');
const sinon = require('sinon');
const { requireRole } = require('../backend/middleware/role.middleware');

console.log('Testing requireRole middleware...');

// Mock request, response and next function
let req, res, next;

const setupMocks = () => {
  req = {
    user: {}
  };
  res = {
    status: sinon.stub().returns(res),
    json: sinon.stub()
  };
  next = sinon.stub();
};

// Test 1: Should allow access if user has the required role
setupMocks();
req.user.role = 'admin';
const middleware = requireRole(['admin']);
middleware(req, res, next);

if (next.calledOnce && !res.status.called) {
  console.log('✅ Test 1 PASSED: User with correct role can access');
} else {
  console.log('❌ Test 1 FAILED: User with correct role cannot access');
}

// Test 2: Should deny access if user does not have the required role
setupMocks();
req.user.role = 'user';
const middleware2 = requireRole(['admin']);
middleware2(req, res, next);

if (!next.calledOnce && res.status.calledWith(403)) {
  console.log('✅ Test 2 PASSED: User with wrong role denied access');
} else {
  console.log('❌ Test 2 FAILED: User with wrong role was allowed access');
}

// Test 3: Should deny access if user has no role
setupMocks();
req.user.role = undefined;
const middleware3 = requireRole(['admin']);
middleware3(req, res, next);

if (!next.calledOnce && res.status.calledWith(401)) {
  console.log('✅ Test 3 PASSED: User with no role denied access');
} else {
  console.log('❌ Test 3 FAILED: User with no role was allowed access');
}

// Test 4: Should allow access if user has one of the required roles
setupMocks();
req.user.role = 'moderator';
const middleware4 = requireRole(['admin', 'moderator']);
middleware4(req, res, next);

if (next.calledOnce && !res.status.called) {
  console.log('✅ Test 4 PASSED: User with one of multiple roles can access');
} else {
  console.log('❌ Test 4 FAILED: User with one of multiple roles cannot access');
}

console.log('Tests completed.');