const axios = require('axios');

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

async function testCreateEmployee() {
  try {
    console.log('=== Testing Employee Creation with User Account ===\n');
    
    // First login as admin
    console.log('1. Logging in as admin...');
    const loginResponse = await axios.post(`${API_URL}/auth/login`, {
      username: 'admin',
      password: 'admin123'
    });
    
    const token = loginResponse.data.token;
    console.log('✓ Login successful, token received\n');
    
    // Create a new employee with user account
    console.log('2. Creating new employee with superuser account...');
    const employeeData = {
      firstName: 'Max',
      lastName: 'Mustermann',
      email: 'max.mustermann@test.com',
      department: 'IT',
      userRole: 'superuser',
      createUser: true
    };
    
    const createResponse = await axios.post(
      `${API_URL}/employees`,
      employeeData,
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      }
    );
    
    console.log('✓ Employee created successfully!');
    console.log('Response:', JSON.stringify(createResponse.data, null, 2));
    
    if (createResponse.data.data?.temporaryPassword) {
      console.log('\n=== IMPORTANT ===');
      console.log('Temporary Password:', createResponse.data.data.temporaryPassword);
      console.log('Employee ID:', createResponse.data.data.id);
      console.log('User ID:', createResponse.data.data.userId);
      console.log('=================\n');
    }
    
    // Try to fetch users to verify decryption works
    console.log('3. Fetching users list to verify decryption...');
    const usersResponse = await axios.get(
      `${API_URL}/admin/users`,
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    );
    
    console.log('✓ Users fetched successfully!');
    console.log('Total users:', usersResponse.data.data.length);
    
    const newUser = usersResponse.data.data.find(u => u.email === employeeData.email);
    if (newUser) {
      console.log('✓ New user found in list:', {
        username: newUser.username,
        email: newUser.email,
        role: newUser.role
      });
    }
    
    console.log('\n✓ All tests passed successfully!');
    
  } catch (error) {
    console.error('\n✗ Test failed:', error.response?.data || error.message);
    if (error.response?.data?.error?.details) {
      console.error('Validation errors:', error.response.data.error.details);
    }
    process.exit(1);
  }
}

// Run the test
testCreateEmployee();