const axios = require('axios');
require('dotenv').config();

const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:2000';

// Test data
const testData = {
  therapist: {
    email: 'therapist@test.com',
    password: 'test123',
    role: 'doctor'
  },
  client: {
    email: 'client@test.com',
    password: 'test123',
    role: 'user'
  },
  admin: {
    email: 'admin@test.com',
    password: 'test123',
    role: 'admin'
  }
};

let tokens = {};
let testPlanId = null;

// Helper function to make API calls
const apiCall = async (method, endpoint, data = null, token = null) => {
  try {
    const config = {
      method,
      url: `${API_BASE_URL}${endpoint}`,
      headers: {}
    };

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    if (data) {
      config.data = data;
      config.headers['Content-Type'] = 'application/json';
    }

    const response = await axios(config);
    return { success: true, data: response.data };
  } catch (error) {
    return { 
      success: false, 
      error: error.response?.data || error.message,
      status: error.response?.status
    };
  }
};

// Test functions
const testLogin = async (userType) => {
  console.log(`\n🔐 Testing ${userType} login...`);
  
  const result = await apiCall('POST', '/api/auth/login', {
    email: testData[userType].email,
    password: testData[userType].password
  });

  if (result.success && result.data.token) {
    tokens[userType] = result.data.token;
    console.log(`✅ ${userType} login successful`);
    return true;
  } else {
    console.log(`❌ ${userType} login failed:`, result.error);
    return false;
  }
};

const testCreateTherapyPlan = async () => {
  console.log('\n📝 Testing therapy plan creation...');
  
  const planData = {
    clientId: '507f1f77bcf86cd799439011', // Mock client ID
    title: 'Test Anxiety Management Plan',
    goals: ['Reduce Symptoms of Anxiety', 'Improve Coping Skills'],
    customGoals: ['Develop mindfulness practices'],
    approaches: ['Cognitive Behavioral Therapy', 'Humanistic Therapy'],
    customApproaches: ['Breathing exercises'],
    numberOfSessions: 8,
    timeline: 'Weekly',
    description: 'A comprehensive plan to help manage anxiety through CBT and mindfulness techniques.',
    therapistNotes: 'Client shows high motivation for change.'
  };

  const result = await apiCall('POST', '/api/therapy-plans/create', planData, tokens.therapist);

  if (result.success) {
    testPlanId = result.data.data._id;
    console.log('✅ Therapy plan created successfully');
    console.log(`   Plan ID: ${testPlanId}`);
    return true;
  } else {
    console.log('❌ Therapy plan creation failed:', result.error);
    return false;
  }
};

const testGetTherapistPlans = async () => {
  console.log('\n📋 Testing get therapist plans...');
  
  const result = await apiCall('GET', '/api/therapy-plans/therapist/plans', null, tokens.therapist);

  if (result.success) {
    console.log('✅ Retrieved therapist plans successfully');
    console.log(`   Found ${result.data.data.plans.length} plans`);
    return true;
  } else {
    console.log('❌ Failed to get therapist plans:', result.error);
    return false;
  }
};

const testSendPlanToClient = async () => {
  if (!testPlanId) {
    console.log('❌ No test plan ID available for sending');
    return false;
  }

  console.log('\n📤 Testing send plan to client...');
  
  const result = await apiCall('POST', `/api/therapy-plans/${testPlanId}/send`, {}, tokens.therapist);

  if (result.success) {
    console.log('✅ Plan sent to client successfully');
    return true;
  } else {
    console.log('❌ Failed to send plan to client:', result.error);
    return false;
  }
};

const testGetClientPlans = async () => {
  console.log('\n👤 Testing get client plans...');
  
  const result = await apiCall('GET', '/api/therapy-plans/client/plans', null, tokens.client);

  if (result.success) {
    console.log('✅ Retrieved client plans successfully');
    console.log(`   Found ${result.data.data.plans.length} plans`);
    return true;
  } else {
    console.log('❌ Failed to get client plans:', result.error);
    return false;
  }
};

const testClientResponse = async () => {
  if (!testPlanId) {
    console.log('❌ No test plan ID available for client response');
    return false;
  }

  console.log('\n💬 Testing client response to plan...');
  
  const responseData = {
    response: 'Accepted',
    acceptanceType: 'Individual',
    notes: 'I am excited to start this therapy plan!'
  };

  const result = await apiCall('POST', `/api/therapy-plans/${testPlanId}/respond`, responseData, tokens.client);

  if (result.success) {
    console.log('✅ Client response recorded successfully');
    return true;
  } else {
    console.log('❌ Failed to record client response:', result.error);
    return false;
  }
};

const testGetAllPlansAdmin = async () => {
  console.log('\n👑 Testing admin get all plans...');
  
  const result = await apiCall('GET', '/api/therapy-plans/admin/all', null, tokens.admin);

  if (result.success) {
    console.log('✅ Retrieved all plans successfully (admin)');
    console.log(`   Found ${result.data.data.plans.length} plans`);
    console.log(`   Statistics:`, result.data.data.statistics);
    return true;
  } else {
    console.log('❌ Failed to get all plans (admin):', result.error);
    return false;
  }
};

const testGetPlanDetails = async () => {
  if (!testPlanId) {
    console.log('❌ No test plan ID available for getting details');
    return false;
  }

  console.log('\n🔍 Testing get plan details...');
  
  const result = await apiCall('GET', `/api/therapy-plans/${testPlanId}`, null, tokens.therapist);

  if (result.success) {
    console.log('✅ Retrieved plan details successfully');
    console.log(`   Plan title: ${result.data.data.title}`);
    console.log(`   Plan status: ${result.data.data.planStatus}`);
    console.log(`   Client response: ${result.data.data.clientResponse}`);
    return true;
  } else {
    console.log('❌ Failed to get plan details:', result.error);
    return false;
  }
};

const testGetTherapyPlanStats = async () => {
  console.log('\n📊 Testing get therapy plan statistics...');
  
  const result = await apiCall('GET', '/api/therapy-plans/stats', null, tokens.therapist);

  if (result.success) {
    console.log('✅ Retrieved therapy plan statistics successfully');
    console.log('   Statistics:', result.data.data.planStats);
    return true;
  } else {
    console.log('❌ Failed to get therapy plan statistics:', result.error);
    return false;
  }
};

const testUpdateTherapyPlan = async () => {
  if (!testPlanId) {
    console.log('❌ No test plan ID available for updating');
    return false;
  }

  console.log('\n✏️ Testing update therapy plan...');
  
  const updateData = {
    description: 'Updated plan description with additional mindfulness techniques.',
    therapistNotes: 'Client is progressing well. Added breathing exercises.'
  };

  const result = await apiCall('PUT', `/api/therapy-plans/${testPlanId}`, updateData, tokens.therapist);

  if (result.success) {
    console.log('✅ Therapy plan updated successfully');
    return true;
  } else {
    console.log('❌ Failed to update therapy plan:', result.error);
    return false;
  }
};

// Main test runner
const runIntegrationTests = async () => {
  console.log('🚀 Starting Therapy Plans Integration Tests');
  console.log('==========================================');

  const tests = [
    () => testLogin('therapist'),
    () => testLogin('client'),
    () => testLogin('admin'),
    testCreateTherapyPlan,
    testGetTherapistPlans,
    testSendPlanToClient,
    testGetClientPlans,
    testClientResponse,
    testGetAllPlansAdmin,
    testGetPlanDetails,
    testGetTherapyPlanStats,
    testUpdateTherapyPlan
  ];

  let passed = 0;
  let failed = 0;

  for (const test of tests) {
    try {
      const result = await test();
      if (result) {
        passed++;
      } else {
        failed++;
      }
    } catch (error) {
      console.log('❌ Test error:', error.message);
      failed++;
    }
    
    // Add delay between tests
    await new Promise(resolve => setTimeout(resolve, 1000));
  }

  console.log('\n📊 Test Results Summary');
  console.log('=======================');
  console.log(`✅ Passed: ${passed}`);
  console.log(`❌ Failed: ${failed}`);
  console.log(`📈 Success Rate: ${((passed / (passed + failed)) * 100).toFixed(1)}%`);

  if (failed === 0) {
    console.log('\n🎉 All tests passed! Therapy Plans feature is working correctly.');
  } else {
    console.log('\n⚠️  Some tests failed. Please check the implementation.');
  }
};

// Error handling
process.on('unhandledRejection', (reason, promise) => {
  console.log('Unhandled Rejection at:', promise, 'reason:', reason);
});

process.on('uncaughtException', (error) => {
  console.log('Uncaught Exception:', error);
  process.exit(1);
});

// Run the tests
if (require.main === module) {
  runIntegrationTests().catch(console.error);
}

module.exports = { runIntegrationTests };
