const axios = require('axios');

const BASE_URL = 'http://localhost:2000/api';

// Test configuration
const testConfig = {
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
};

// Mock JWT token for testing (you'll need to replace this with a real token)
const mockToken = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY3NjQzZjI4ZjA5YzQyMDAwOGY4YzQyYSIsInJvbGUiOiJkb2N0b3IiLCJpYXQiOjE3MzQ2MjQ5OTJ9.example';

const authHeaders = {
  ...testConfig.headers,
  'Authorization': mockToken
};

// Test results storage
const testResults = {
  passed: 0,
  failed: 0,
  errors: []
};

// Helper function to run tests
async function runTest(testName, testFunction) {
  try {
    console.log(`\n🧪 Testing: ${testName}`);
    await testFunction();
    console.log(`✅ ${testName} - PASSED`);
    testResults.passed++;
  } catch (error) {
    console.log(`❌ ${testName} - FAILED`);
    console.log(`   Error: ${error.message}`);
    testResults.failed++;
    testResults.errors.push({ test: testName, error: error.message });
  }
}

// Test server health
async function testServerHealth() {
  const response = await axios.get(`${BASE_URL.replace('/api', '')}/`, testConfig);
  if (response.status !== 200) {
    throw new Error(`Server health check failed with status: ${response.status}`);
  }
}

// Test therapist profile endpoints
async function testTherapistProfileEndpoints() {
  // Test get profile (should return 401 without auth)
  try {
    await axios.get(`${BASE_URL}/doctor/profile`, testConfig);
    throw new Error('Should have returned 401 without auth');
  } catch (error) {
    if (error.response && error.response.status === 401) {
      // Expected behavior
    } else {
      throw error;
    }
  }
}

// Test matching system endpoints
async function testMatchingEndpoints() {
  // Test find therapists (should return 401 without auth)
  try {
    await axios.post(`${BASE_URL}/appointments/find-therapists`, {
      preferredMode: "Online",
      sessionType: "Individual Therapy",
      preferredDate: "2024-12-25",
      preferredTime: "10:00"
    }, testConfig);
    throw new Error('Should have returned 401 without auth');
  } catch (error) {
    if (error.response && error.response.status === 401) {
      // Expected behavior
    } else {
      throw error;
    }
  }
}

// Test admin approval endpoints
async function testAdminApprovalEndpoints() {
  // Test get pending approvals (should return 401 without auth)
  try {
    await axios.get(`${BASE_URL}/admin/therapists/approvals`, testConfig);
    throw new Error('Should have returned 401 without auth');
  } catch (error) {
    if (error.response && error.response.status === 401) {
      // Expected behavior
    } else {
      throw error;
    }
  }
}

// Test database model validation
async function testDatabaseModels() {
  // This would require a database connection test
  // For now, we'll just check if the models can be imported
  const TherapistProfile = require('./models/TherapistProfile');
  if (!TherapistProfile) {
    throw new Error('TherapistProfile model not found');
  }
}

// Test route imports
async function testRouteImports() {
  const therapistProfileRoutes = require('./routes/doctor/therapistProfileRoutes');
  const matchingRoutes = require('./routes/appointment/matchingRoutes');
  const approvalRoutes = require('./routes/admin/therapistApprovalRoutes');
  
  if (!therapistProfileRoutes || !matchingRoutes || !approvalRoutes) {
    throw new Error('One or more route modules failed to import');
  }
}

// Test controller imports
async function testControllerImports() {
  const therapistProfileController = require('./controller/doctor/therapistProfileController');
  const matchingController = require('./controller/appointment/matchingController');
  const approvalController = require('./controller/admin/therapistApprovalController');
  
  if (!therapistProfileController || !matchingController || !approvalController) {
    throw new Error('One or more controller modules failed to import');
  }
}

// Main test runner
async function runAllTests() {
  console.log('🚀 Starting API Integration Tests...\n');
  
  // Test imports first (these don't require server to be running)
  await runTest('Database Models Import', testDatabaseModels);
  await runTest('Route Modules Import', testRouteImports);
  await runTest('Controller Modules Import', testControllerImports);
  
  // Test server endpoints (these require server to be running)
  console.log('\n📡 Testing Server Endpoints (requires server to be running)...');
  
  await runTest('Server Health Check', testServerHealth);
  await runTest('Therapist Profile Endpoints', testTherapistProfileEndpoints);
  await runTest('Matching System Endpoints', testMatchingEndpoints);
  await runTest('Admin Approval Endpoints', testAdminApprovalEndpoints);
  
  // Print results
  console.log('\n📊 Test Results Summary:');
  console.log(`✅ Passed: ${testResults.passed}`);
  console.log(`❌ Failed: ${testResults.failed}`);
  console.log(`📈 Success Rate: ${((testResults.passed / (testResults.passed + testResults.failed)) * 100).toFixed(1)}%`);
  
  if (testResults.errors.length > 0) {
    console.log('\n🔍 Failed Tests Details:');
    testResults.errors.forEach(error => {
      console.log(`   - ${error.test}: ${error.error}`);
    });
  }
  
  console.log('\n💡 Notes:');
  console.log('   - Server endpoint tests require the backend server to be running');
  console.log('   - Authentication tests expect 401 responses (this is correct behavior)');
  console.log('   - To test authenticated endpoints, update the mockToken with a real JWT');
  
  return testResults.failed === 0;
}

// Export for use in other files
module.exports = { runAllTests };

// Run tests if this file is executed directly
if (require.main === module) {
  runAllTests()
    .then(success => {
      process.exit(success ? 0 : 1);
    })
    .catch(error => {
      console.error('Test runner failed:', error);
      process.exit(1);
    });
}
