const axios = require('axios');

const API_BASE_URL = 'http://localhost:3000/api';

// Test data
const testRole = {
  name: 'Test Manager',
  description: 'A test role for testing the role management system',
  level: 60,
  permissions: [1, 2, 3] // Some basic permissions
};

async function testRoleAPI() {
  console.log('🧪 Testing Role Management API...\n');

  try {
    // Test 1: Get all roles
    console.log('1️⃣ Testing GET /roles...');
    const rolesResponse = await axios.get(`${API_BASE_URL}/roles`);
    console.log('✅ Success:', rolesResponse.data);
    console.log('');

    // Test 2: Get roles with permissions
    console.log('2️⃣ Testing GET /roles/with-permissions...');
    const rolesWithPermissionsResponse = await axios.get(`${API_BASE_URL}/roles/with-permissions`);
    console.log('✅ Success:', rolesWithPermissionsResponse.data);
    console.log('');

    // Test 3: Get permissions
    console.log('3️⃣ Testing GET /permissions...');
    const permissionsResponse = await axios.get(`${API_BASE_URL}/permissions`);
    console.log('✅ Success:', permissionsResponse.data);
    console.log('');

    // Test 4: Create a new role
    console.log('4️⃣ Testing POST /roles (Create role)...');
    const createResponse = await axios.post(`${API_BASE_URL}/roles`, testRole);
    console.log('✅ Success:', createResponse.data);
    const createdRoleId = createResponse.data.data.role.id;
    console.log('');

    // Test 5: Get role by ID
    console.log('5️⃣ Testing GET /roles/:id...');
    const getRoleResponse = await axios.get(`${API_BASE_URL}/roles/${createdRoleId}`);
    console.log('✅ Success:', getRoleResponse.data);
    console.log('');

    // Test 6: Update role
    console.log('6️⃣ Testing PUT /roles/:id (Update role)...');
    const updateData = {
      ...testRole,
      name: 'Updated Test Manager',
      description: 'Updated description for test role'
    };
    const updateResponse = await axios.put(`${API_BASE_URL}/roles/${createdRoleId}`, updateData);
    console.log('✅ Success:', updateResponse.data);
    console.log('');

    // Test 7: Delete role
    console.log('7️⃣ Testing DELETE /roles/:id...');
    const deleteResponse = await axios.delete(`${API_BASE_URL}/roles/${createdRoleId}`);
    console.log('✅ Success:', deleteResponse.data);
    console.log('');

    console.log('🎉 All tests passed! Role Management API is working correctly.');

  } catch (error) {
    console.error('❌ Test failed:', error.response?.data || error.message);
  }
}

// Run the test
testRoleAPI();
