const axios = require('axios')

const BASE_URL = 'http://localhost:3000/api'

// Test configuration
const TEST_USER = {
  login_id: 'test_user',
  password: 'wrong_password'
}

let authToken = null

async function testSecurityAPI() {
  console.log('🧪 Testing Security API Implementation\n')

  try {
    // Step 1: Test failed login (this should create a failed_login_attempts record)
    console.log('1️⃣  Testing Failed Login Tracking...')
    try {
      await axios.post(`${BASE_URL}/auth/login`, TEST_USER)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        console.log('   ✅ Failed login attempt recorded (expected 401 error)')
      } else {
        throw error
      }
    }

    // Step 2: Login with correct credentials
    console.log('\n2️⃣  Logging in with correct credentials...')
    console.log('   Please enter valid credentials:')
    
    // Use environment variables or prompt for credentials
    const LOGIN_ID = process.env.TEST_LOGIN_ID || 'super_admin'
    const PASSWORD = process.env.TEST_PASSWORD || 'admin123'
    
    const loginResponse = await axios.post(`${BASE_URL}/auth/login`, {
      login_id: LOGIN_ID,
      password: PASSWORD
    })
    
    if (loginResponse.data.status === 'success') {
      authToken = loginResponse.data.data.token
      console.log('   ✅ Login successful')
      console.log(`   👤 Logged in as: ${loginResponse.data.data.user.name}`)
    }

    // Step 3: Test Get Failed Logins (24h)
    console.log('\n3️⃣  Testing GET /api/security/failed-logins...')
    const failedLoginsResponse = await axios.get(
      `${BASE_URL}/security/failed-logins?hours=24`,
      {
        headers: { Authorization: `Bearer ${authToken}` }
      }
    )
    
    if (failedLoginsResponse.data.status === 'success') {
      console.log('   ✅ Failed logins endpoint working')
      console.log(`   📊 Total attempts in last 24h: ${failedLoginsResponse.data.data.summary.total_attempts}`)
      console.log(`   👥 Unique users: ${failedLoginsResponse.data.data.summary.unique_users}`)
      console.log(`   🌐 Unique IPs: ${failedLoginsResponse.data.data.summary.unique_ips}`)
      
      if (failedLoginsResponse.data.data.attempts.length > 0) {
        console.log('\n   Recent Failed Login Attempts:')
        failedLoginsResponse.data.data.attempts.slice(0, 5).forEach((attempt, index) => {
          console.log(`   ${index + 1}. ${attempt.login_id} - ${attempt.reason} (${attempt.attempted_at})`)
        })
      }
    }

    // Step 4: Test Get Password Changes (7d)
    console.log('\n4️⃣  Testing GET /api/security/password-changes...')
    const passwordChangesResponse = await axios.get(
      `${BASE_URL}/security/password-changes?days=7`,
      {
        headers: { Authorization: `Bearer ${authToken}` }
      }
    )
    
    if (passwordChangesResponse.data.status === 'success') {
      console.log('   ✅ Password changes endpoint working')
      console.log(`   📊 Total changes in last 7 days: ${passwordChangesResponse.data.data.summary.total_changes}`)
      console.log(`   👥 Unique users: ${passwordChangesResponse.data.data.summary.unique_users}`)
      console.log(`   🔐 Self changes: ${passwordChangesResponse.data.data.summary.self_changes}`)
      console.log(`   🔧 Admin resets: ${passwordChangesResponse.data.data.summary.admin_resets}`)
      
      if (passwordChangesResponse.data.data.changes.length > 0) {
        console.log('\n   Recent Password Changes:')
        passwordChangesResponse.data.data.changes.slice(0, 5).forEach((change, index) => {
          console.log(`   ${index + 1}. ${change.user_name} - ${change.change_type} (${change.changed_at})`)
        })
      }
    }

    // Step 5: Test Security Overview
    console.log('\n5️⃣  Testing GET /api/security/overview...')
    const overviewResponse = await axios.get(
      `${BASE_URL}/security/overview`,
      {
        headers: { Authorization: `Bearer ${authToken}` }
      }
    )
    
    if (overviewResponse.data.status === 'success') {
      console.log('   ✅ Security overview endpoint working')
      console.log('\n   📊 Security Overview:')
      console.log('   Failed Logins (24h):')
      console.log(`     - Total attempts: ${overviewResponse.data.data.failed_logins_24h.total_attempts}`)
      console.log('   Password Changes (7d):')
      console.log(`     - Total changes: ${overviewResponse.data.data.password_changes_7d.total_changes}`)
      console.log(`   Recent Events: ${overviewResponse.data.data.recent_events.length}`)
      
      if (overviewResponse.data.data.recent_events.length > 0) {
        console.log('\n   Recent Security Events:')
        overviewResponse.data.data.recent_events.slice(0, 5).forEach((event, index) => {
          console.log(`   ${index + 1}. [${event.event_type}] ${event.user_identifier} - ${event.details}`)
        })
      }
    }

    // Step 6: Test with different time ranges
    console.log('\n6️⃣  Testing different time ranges...')
    
    // Test 48 hours
    const failedLogins48h = await axios.get(
      `${BASE_URL}/security/failed-logins?hours=48`,
      {
        headers: { Authorization: `Bearer ${authToken}` }
      }
    )
    console.log(`   ✅ Failed logins (48h): ${failedLogins48h.data.data.summary.total_attempts} attempts`)
    
    // Test 30 days
    const passwordChanges30d = await axios.get(
      `${BASE_URL}/security/password-changes?days=30`,
      {
        headers: { Authorization: `Bearer ${authToken}` }
      }
    )
    console.log(`   ✅ Password changes (30d): ${passwordChanges30d.data.data.summary.total_changes} changes`)

    // Step 7: Test error handling
    console.log('\n7️⃣  Testing error handling...')
    
    // Test invalid hours parameter
    try {
      await axios.get(
        `${BASE_URL}/security/failed-logins?hours=1000`,
        {
          headers: { Authorization: `Bearer ${authToken}` }
        }
      )
    } catch (error) {
      if (error.response && error.response.status === 400) {
        console.log('   ✅ Invalid hours parameter rejected correctly')
      }
    }
    
    // Test invalid days parameter
    try {
      await axios.get(
        `${BASE_URL}/security/password-changes?days=500`,
        {
          headers: { Authorization: `Bearer ${authToken}` }
        }
      )
    } catch (error) {
      if (error.response && error.response.status === 400) {
        console.log('   ✅ Invalid days parameter rejected correctly')
      }
    }
    
    // Test without authentication
    try {
      await axios.get(`${BASE_URL}/security/failed-logins`)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        console.log('   ✅ Unauthenticated request rejected correctly')
      }
    }

    console.log('\n✅ All Security API tests passed successfully!\n')
    console.log('📚 Documentation: backend/SECURITY_API_DOCUMENTATION.md')
    console.log('📝 Summary: backend/SECURITY_IMPLEMENTATION_SUMMARY.md')

  } catch (error) {
    console.error('\n❌ Test failed:', error.message)
    if (error.response) {
      console.error('Response:', error.response.data)
    }
    process.exit(1)
  }
}

// Check if server is running
async function checkServer() {
  try {
    await axios.get(`${BASE_URL}/health`)
    return true
  } catch (error) {
    return false
  }
}

// Main execution
async function main() {
  console.log('Checking if server is running...')
  const serverRunning = await checkServer()
  
  if (!serverRunning) {
    console.error('❌ Server is not running!')
    console.error('Please start the server first: npm start')
    process.exit(1)
  }
  
  console.log('✅ Server is running\n')
  await testSecurityAPI()
}

main()

