const http = require('http');

console.log('🧪 Testing Security Overview endpoint with authentication...\n');

// First, login to get a real token
const loginData = JSON.stringify({
  login_id: 'super_admin',
  password: 'admin123'
});

const loginOptions = {
  hostname: 'localhost',
  port: 83,
  path: '/api/auth/login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': loginData.length
  }
};

const loginReq = http.request(loginOptions, (res) => {
  let data = '';
  res.on('data', chunk => data += chunk);
  res.on('end', () => {
    try {
      const loginResponse = JSON.parse(data);
      
      if (loginResponse.status === 'success' && loginResponse.data.token) {
        const token = loginResponse.data.token;
        console.log('✅ Login successful\n');
        
        // Now test the security overview endpoint
        const securityOptions = {
          hostname: 'localhost',
          port: 83,
          path: '/api/security/overview',
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        };
        
        const securityReq = http.request(securityOptions, (res) => {
          let secData = '';
          res.on('data', chunk => secData += chunk);
          res.on('end', () => {
            try {
              const securityResponse = JSON.parse(secData);
              
              console.log('📊 Security Overview Response:');
              console.log('   Status:', securityResponse.status);
              
              if (securityResponse.status === 'success') {
                console.log('\n✅ SUCCESS! Security API is working!\n');
                console.log('Failed Logins (24h):');
                console.log('   Total attempts:', securityResponse.data.failed_logins_24h.total_attempts);
                console.log('   Unique users:', securityResponse.data.failed_logins_24h.unique_users);
                console.log('   Unique IPs:', securityResponse.data.failed_logins_24h.unique_ips);
                
                console.log('\nPassword Changes (7d):');
                console.log('   Total changes:', securityResponse.data.password_changes_7d.total_changes);
                console.log('   Self-initiated:', securityResponse.data.password_changes_7d.self_changes);
                console.log('   Admin resets:', securityResponse.data.password_changes_7d.admin_resets);
                
                console.log('\nRecent Events:', securityResponse.data.recent_events.length);
                if (securityResponse.data.recent_events.length > 0) {
                  console.log('\nLast 3 events:');
                  securityResponse.data.recent_events.slice(0, 3).forEach((event, i) => {
                    console.log(`   ${i + 1}. [${event.event_type}] ${event.user_identifier} - ${event.details}`);
                  });
                }
              } else {
                console.log('\n❌ ERROR:', securityResponse.message);
                if (securityResponse.stack) {
                  console.log('\nStack trace:');
                  console.log(securityResponse.stack);
                }
              }
            } catch (e) {
              console.log('❌ Parse error:', e.message);
              console.log('Raw response:', secData);
            }
          });
        });
        
        securityReq.on('error', (e) => {
          console.log('❌ Request error:', e.message);
        });
        
        securityReq.end();
      } else {
        console.log('❌ Login failed:', loginResponse.message);
      }
    } catch (e) {
      console.log('❌ Parse error:', e.message);
      console.log('Raw response:', data);
    }
  });
});

loginReq.on('error', (e) => {
  console.log('❌ Login request error:', e.message);
});

loginReq.write(loginData);
loginReq.end();

