const axios = require('axios');

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

async function testEmployeeCreation() {
  try {
    console.log('1. Testing login...');
    // First, login to get a token
    const loginResponse = await axios.post(`${API_URL}/auth/login`, {
      username: 'admin',
      password: 'ChangeMe123!@#'
    });

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

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

    console.log('\n2. Creating a test employee...');
    // Create a test employee
    const employeeData = {
      firstName: 'Max',
      lastName: 'Mustermann',
      employeeNumber: 'EMP-' + Date.now(),
      position: 'Software Developer',
      department: 'IT',
      email: 'max.mustermann@example.com',
      phone: '+49 123 456789',
      mobile: '+49 170 123456',
      office: 'Building A, Room 123',
      availability: 'available',
      skills: [],
      languages: [
        { code: 'de', level: 'native' },
        { code: 'en', level: 'fluent' }
      ],
      specializations: ['Backend Development', 'Database Design'],
      clearance: {
        level: 'confidential',
        validUntil: '2025-12-31',
        issuedDate: '2024-01-01'
      },
      createUser: true,
      userRole: 'user'
    };

    const createResponse = await axios.post(
      `${API_URL}/employees`,
      employeeData,
      { headers }
    );

    console.log('✅ Employee created successfully!');
    console.log('Employee ID:', createResponse.data.data.id);
    if (createResponse.data.data.temporaryPassword) {
      console.log('Temporary Password:', createResponse.data.data.temporaryPassword);
    }

    // Fetch the created employee
    console.log('\n3. Fetching created employee...');
    const getResponse = await axios.get(
      `${API_URL}/employees/${createResponse.data.data.id}`,
      { headers }
    );

    console.log('✅ Employee fetched successfully!');
    console.log('Employee Data:');
    console.log('- Name:', getResponse.data.data.firstName, getResponse.data.data.lastName);
    console.log('- Email (decrypted):', getResponse.data.data.email);
    console.log('- Phone (decrypted):', getResponse.data.data.phone);
    console.log('- Department:', getResponse.data.data.department);
    console.log('- Clearance:', getResponse.data.data.clearance);

    console.log('\n✅ All tests passed! Employee creation and encryption working correctly.');

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

testEmployeeCreation();