#!/usr/bin/env node

/**
 * Test script for unified tech stack recommendations with user authentication
 * Tests both anonymous and authenticated user scenarios
 */

const axios = require('axios');

const UNIFIED_SERVICE_URL = 'http://localhost:8013';
const USER_AUTH_URL = 'http://localhost:8011';
const COMPREHENSIVE_ENDPOINT = '/api/unified/comprehensive-recommendations';

// Test data
const testRequest = {
  template: {
    id: 'test-template-123',
    title: 'E-commerce Platform',
    description: 'A comprehensive e-commerce solution',
    category: 'E-commerce',
    type: 'web-app'
  },
  features: [
    {
      id: 'feature-1',
      name: 'User Authentication',
      description: 'Secure user login and registration system',
      feature_type: 'essential',
      complexity: 'medium',
      business_rules: ['Users must verify email', 'Password must meet security requirements'],
      technical_requirements: ['JWT tokens', 'Password hashing', 'Email verification']
    },
    {
      id: 'feature-2',
      name: 'Product Catalog',
      description: 'Product listing and search functionality',
      feature_type: 'essential',
      complexity: 'medium',
      business_rules: ['Products must have valid pricing', 'Search must be fast'],
      technical_requirements: ['Database indexing', 'Search optimization']
    }
  ],
  businessContext: {
    questions: [
      {
        question: 'What is your target audience?',
        answer: 'Small to medium businesses selling products online'
      },
      {
        question: 'What is your expected user volume?',
        answer: 'We expect around 10,000 users initially, growing to 100,000 within a year'
      }
    ]
  },
  projectName: 'E-commerce Platform',
  projectType: 'E-commerce',
  templateId: 'test-template-123',
  budget: 15000,
  domain: 'ecommerce',
  includeClaude: true,
  includeTemplateBased: true,
  includeDomainBased: true
};

async function loginUser() {
  try {
    console.log('🔐 Logging in test user...');
    const response = await axios.post(`${USER_AUTH_URL}/api/auth/login`, {
      email: 'test@tech4biz.com',
      password: 'admin123'
    }, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response.data.success) {
      console.log('✅ User logged in successfully');
      return response.data.data.access_token;
    } else {
      console.log('❌ Login failed:', response.data.message);
      return null;
    }
  } catch (error) {
    console.log('❌ Login error:', error.response?.data?.message || error.message);
    return null;
  }
}

async function testAnonymousRecommendations() {
  console.log('\n🧪 Testing Anonymous Recommendations');
  console.log('=' .repeat(50));
  
  try {
    const response = await axios.post(
      `${UNIFIED_SERVICE_URL}${COMPREHENSIVE_ENDPOINT}`,
      testRequest,
      {
        timeout: 60000,
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    console.log('✅ Anonymous recommendations received successfully!');
    console.log('📊 Response Status:', response.status);
    
    if (response.data.success) {
      console.log('✅ Success: true');
      console.log('📝 Message:', response.data.message);
      console.log('👤 User ID in response:', response.data.data?.metadata?.userId || 'null (anonymous)');
    } else {
      console.log('❌ Success: false');
      console.log('Error:', response.data.error);
    }

  } catch (error) {
    console.log('❌ Anonymous test failed!');
    console.log('Error:', error.message);
    
    if (error.response) {
      console.log('Response Status:', error.response.status);
      console.log('Response Data:', JSON.stringify(error.response.data, null, 2));
    }
  }
}

async function testAuthenticatedRecommendations(accessToken) {
  console.log('\n🔐 Testing Authenticated User Recommendations');
  console.log('=' .repeat(50));
  
  try {
    const response = await axios.post(
      `${UNIFIED_SERVICE_URL}${COMPREHENSIVE_ENDPOINT}`,
      testRequest,
      {
        timeout: 60000,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${accessToken}`
        }
      }
    );

    console.log('✅ Authenticated recommendations received successfully!');
    console.log('📊 Response Status:', response.status);
    
    if (response.data.success) {
      console.log('✅ Success: true');
      console.log('📝 Message:', response.data.message);
      console.log('👤 User ID in response:', response.data.data?.metadata?.userId || 'null');
    } else {
      console.log('❌ Success: false');
      console.log('Error:', response.data.error);
    }

  } catch (error) {
    console.log('❌ Authenticated test failed!');
    console.log('Error:', error.message);
    
    if (error.response) {
      console.log('Response Status:', error.response.status);
      console.log('Response Data:', JSON.stringify(error.response.data, null, 2));
    }
  }
}

async function testUserStats(accessToken) {
  console.log('\n📊 Testing User Statistics');
  console.log('=' .repeat(50));
  
  try {
    const response = await axios.get(
      `${UNIFIED_SERVICE_URL}/api/unified/user/stats`,
      {
        timeout: 10000,
        headers: {
          'Authorization': `Bearer ${accessToken}`
        }
      }
    );

    console.log('✅ User stats retrieved successfully!');
    console.log('📊 Response Status:', response.status);
    
    if (response.data.success) {
      console.log('✅ Success: true');
      console.log('📊 Stats:', JSON.stringify(response.data.data, null, 2));
    } else {
      console.log('❌ Success: false');
      console.log('Error:', response.data.error);
    }

  } catch (error) {
    console.log('❌ User stats test failed!');
    console.log('Error:', error.message);
    
    if (error.response) {
      console.log('Response Status:', error.response.status);
      console.log('Response Data:', JSON.stringify(error.response.data, null, 2));
    }
  }
}

async function testUserHistory(accessToken) {
  console.log('\n📚 Testing User Recommendation History');
  console.log('=' .repeat(50));
  
  try {
    const response = await axios.get(
      `${UNIFIED_SERVICE_URL}/api/unified/user/recommendations`,
      {
        timeout: 10000,
        headers: {
          'Authorization': `Bearer ${accessToken}`
        }
      }
    );

    console.log('✅ User history retrieved successfully!');
    console.log('📊 Response Status:', response.status);
    
    if (response.data.success) {
      console.log('✅ Success: true');
      console.log('📚 History count:', response.data.data?.length || 0);
    } else {
      console.log('❌ Success: false');
      console.log('Error:', response.data.error);
    }

  } catch (error) {
    console.log('❌ User history test failed!');
    console.log('Error:', error.message);
    
    if (error.response) {
      console.log('Response Status:', error.response.status);
      console.log('Response Data:', JSON.stringify(error.response.data, null, 2));
    }
  }
}

async function testServiceHealth() {
  console.log('\n🏥 Testing Service Health');
  console.log('=' .repeat(50));
  
  try {
    const response = await axios.get(`${UNIFIED_SERVICE_URL}/health`, { timeout: 5000 });
    console.log('✅ Unified service is healthy');
    console.log(`   Status: ${response.data.status}`);
    console.log(`   Version: ${response.data.version}`);
    
    // Test status endpoint
    const statusResponse = await axios.get(`${UNIFIED_SERVICE_URL}/api/unified/status`, { timeout: 5000 });
    console.log('✅ Service status endpoint working');
    console.log(`   Overall Status: ${statusResponse.data.data?.overallStatus}`);
    console.log(`   Template Manager: ${statusResponse.data.data?.templateManager?.status}`);
    console.log(`   Tech Stack Selector: ${statusResponse.data.data?.techStackSelector?.status}`);
    console.log(`   User Auth: ${statusResponse.data.data?.userAuth?.status}`);
    
  } catch (error) {
    console.log('❌ Service health check failed!');
    console.log('Error:', error.message);
  }
}

async function runAllTests() {
  console.log('🧪 Testing Unified Tech Stack Service with User Authentication');
  console.log('=' .repeat(70));
  
  // Test service health first
  await testServiceHealth();
  
  // Test anonymous recommendations
  await testAnonymousRecommendations();
  
  // Login and test authenticated features
  const accessToken = await loginUser();
  
  if (accessToken) {
    await testAuthenticatedRecommendations(accessToken);
    await testUserStats(accessToken);
    await testUserHistory(accessToken);
  } else {
    console.log('\n⚠️  Skipping authenticated tests - login failed');
  }
  
  console.log('\n🏁 All tests completed!');
}

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

module.exports = { runAllTests };
