const axios = require('axios');

const API_URL = 'http://localhost:3005/api';

async function testUserAdmin() {
  try {
    console.log('🧪 Testing Admin Panel User Management...\n');

    console.log('1. Testing admin login...');
    const loginResponse = await axios.post(`${API_URL}/auth/login`, {
      username: 'admin',
      password: 'ChangeMe123!@#'
    });

    const token = loginResponse.data.data.token.accessToken;
    console.log('✅ Admin login successful');

    const headers = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };

    console.log('\n2. Testing user list endpoint...');
    const usersResponse = await axios.get(`${API_URL}/admin/users`, { headers });
    console.log('✅ User list fetched successfully');
    console.log(`   Found ${usersResponse.data.data.length} users`);

    console.log('\n3. Creating test employee with user account...');
    const newEmployee = {
      firstName: 'AdminTest',
      lastName: 'User',
      email: 'admin.test@example.com',
      department: 'Testing',
      createUser: true,
      userRole: 'user'
    };

    const createResponse = await axios.post(`${API_URL}/employees`, newEmployee, { headers });
    console.log('✅ Employee with user account created');
    const newUserId = createResponse.data.data.userId;
    const tempPassword = createResponse.data.data.temporaryPassword;
    console.log(`   User ID: ${newUserId}`);
    console.log(`   Temp Password: ${tempPassword}`);

    if (newUserId) {
      console.log('\n4. Testing role change...');
      await axios.put(`${API_URL}/admin/users/${newUserId}/role`, 
        { role: 'superuser' }, 
        { headers }
      );
      console.log('✅ User role changed to superuser');

      console.log('\n5. Testing password reset...');
      const resetResponse = await axios.post(`${API_URL}/admin/users/${newUserId}/reset-password`, 
        { }, 
        { headers }
      );
      console.log('✅ Password reset successfully');
      console.log(`   New temp password: ${resetResponse.data.data.temporaryPassword}`);

      console.log('\n6. Testing status toggle...');
      await axios.put(`${API_URL}/admin/users/${newUserId}/status`, 
        { isActive: false }, 
        { headers }
      );
      console.log('✅ User deactivated');

      await axios.put(`${API_URL}/admin/users/${newUserId}/status`, 
        { isActive: true }, 
        { headers }
      );
      console.log('✅ User reactivated');

      console.log('\n7. Cleaning up - deleting test user...');
      await axios.delete(`${API_URL}/admin/users/${newUserId}`, { headers });
      console.log('✅ Test user deleted');
    }

    console.log('\n🎉 All Admin Panel User Management tests passed!');

  } catch (error) {
    console.error('\n❌ Test failed:', error.response?.data || error.message);
    if (error.response?.status) {
      console.error(`   Status: ${error.response.status}`);
    }
  }
}

testUserAdmin();