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

// API base URL
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:5000/api';

// Test data
const testData = {
    newUser: {
        name: 'Test User',
        dob: '1995-01-01',
        mobile: '+9999999999',
        password: 'testpassword123'
    },
    existingUser: {
        mobile: '+1234567890',
        password: 'password123'
    },
    unverifiedUser: {
        mobile: '+1234567893',
        password: 'password101'
    },
    otpData: {
        mobile: '+1234567892',
        otp: '123456'
    }
};

// Helper function to make API requests
const makeRequest = async (method, endpoint, data = null) => {
    try {
        const config = {
            method,
            url: `${BASE_URL}${endpoint}`,
            headers: {
                'Content-Type': 'application/json'
            }
        };
        
        if (data) {
            config.data = data;
        }
        
        const response = await axios(config);
        return { success: true, data: response.data, status: response.status };
    } catch (error) {
        return { 
            success: false, 
            error: error.response?.data || error.message, 
            status: error.response?.status || 500 
        };
    }
};

// Test functions
const testGetAllUsers = async () => {
    console.log('\n🔍 Testing: Get All Users');
    console.log('=' .repeat(50));
    
    const result = await makeRequest('GET', '/users/all');
    
    if (result.success) {
        console.log('✅ Success!');
        console.log(`📊 Total users: ${result.data.data.total}`);
        console.log('👥 Users:');
        result.data.data.users.forEach((user, index) => {
            console.log(`   ${index + 1}. ${user.name} (${user.mobile}) - ${user.isVerified ? 'Verified' : 'Unverified'}`);
        });
    } else {
        console.log('❌ Failed:', result.error);
    }
};

const testUserRegistration = async () => {
    console.log('\n📝 Testing: User Registration');
    console.log('=' .repeat(50));
    
    const result = await makeRequest('POST', '/users/register', testData.newUser);
    
    if (result.success) {
        console.log('✅ Registration successful!');
        console.log('📱 User ID:', result.data.data.userId);
        console.log('👤 Name:', result.data.data.name);
        console.log('📞 Mobile:', result.data.data.mobile);
    } else {
        console.log('❌ Registration failed:', result.error);
    }
};

const testOTPVerification = async () => {
    console.log('\n🔐 Testing: OTP Verification');
    console.log('=' .repeat(50));
    
    const result = await makeRequest('POST', '/users/verify-otp', testData.otpData);
    
    if (result.success) {
        console.log('✅ OTP verification successful!');
        console.log('👤 User ID:', result.data.data.userId);
    } else {
        console.log('❌ OTP verification failed:', result.error);
    }
};

const testUserLogin = async () => {
    console.log('\n🔑 Testing: User Login (Verified User)');
    console.log('=' .repeat(50));
    
    const result = await makeRequest('POST', '/auth/login', testData.existingUser);
    
    if (result.success) {
        console.log('✅ Login successful!');
        console.log('👤 User:', result.data.data.user.name);
        console.log('📞 Mobile:', result.data.data.user.mobile);
        console.log('🎫 Token received:', result.data.data.token ? 'Yes' : 'No');
    } else {
        console.log('❌ Login failed:', result.error);
    }
};

const testUnverifiedUserLogin = async () => {
    console.log('\n🚫 Testing: Unverified User Login');
    console.log('=' .repeat(50));
    
    const result = await makeRequest('POST', '/auth/login', testData.unverifiedUser);
    
    if (result.success) {
        console.log('✅ Login successful!');
    } else {
        console.log('❌ Login failed (expected):', result.error.message);
    }
};

const testGetUserProfile = async () => {
    console.log('\n👤 Testing: Get User Profile');
    console.log('=' .repeat(50));
    
    // First get a user ID from the all users endpoint
    const allUsersResult = await makeRequest('GET', '/users/all');
    
    if (allUsersResult.success && allUsersResult.data.data.users.length > 0) {
        const userId = allUsersResult.data.data.users[0]._id;
        console.log('🔍 Testing with User ID:', userId);
        
        const result = await makeRequest('GET', `/auth/profile/${userId}`);
        
        if (result.success) {
            console.log('✅ Profile retrieved successfully!');
            console.log('👤 User:', result.data.data.name);
            console.log('📞 Mobile:', result.data.data.mobile);
            console.log('📅 DOB:', result.data.data.dob);
        } else {
            console.log('❌ Profile retrieval failed:', result.error);
        }
    } else {
        console.log('❌ Could not get user ID for profile test');
        console.log('📊 All users result:', allUsersResult.success ? 'Success' : 'Failed');
        if (allUsersResult.success) {
            console.log('📝 Users count:', allUsersResult.data.data.users.length);
        }
    }
};

const testGetUserByMobile = async () => {
    console.log('\n📱 Testing: Get User by Mobile');
    console.log('=' .repeat(50));
    
    // Use a mobile number without the + sign to avoid URL encoding issues
    const mobileNumber = testData.existingUser.mobile.replace('+', '');
    console.log('🔍 Testing with mobile:', mobileNumber);
    
    const result = await makeRequest('GET', `/users/mobile/${mobileNumber}`);
    
    if (result.success) {
        console.log('✅ User found!');
        console.log('👤 Name:', result.data.data.name);
        console.log('📞 Mobile:', result.data.data.mobile);
        console.log('✅ Verified:', result.data.data.isVerified);
    } else {
        console.log('❌ User not found:', result.error);
    }
};

const testResendOTP = async () => {
    console.log('\n📲 Testing: Resend OTP');
    console.log('=' .repeat(50));
    
    const result = await makeRequest('POST', '/users/resend-otp', { mobile: testData.unverifiedUser.mobile });
    
    if (result.success) {
        console.log('✅ OTP resent successfully!');
    } else {
        console.log('❌ OTP resend failed:', result.error);
    }
};

// Main test runner
const runAllTests = async () => {
    console.log('🚀 Starting API Tests');
    console.log('=' .repeat(80));
    console.log(`🌐 Base URL: ${BASE_URL}`);
    console.log(`⏰ Test Time: ${new Date().toLocaleString()}`);
    
    try {
        // Test all endpoints
        await testGetAllUsers();
        await testUserRegistration();
        await testOTPVerification();
        await testUserLogin();
        await testUnverifiedUserLogin();
        await testGetUserProfile();
        await testGetUserByMobile();
        await testResendOTP();
        
        console.log('\n🎉 All tests completed!');
        console.log('=' .repeat(80));
        
    } catch (error) {
        console.error('❌ Test runner error:', error.message);
    }
};

// Check if axios is available
const checkDependencies = () => {
    try {
        require('axios');
        return true;
    } catch (error) {
        console.log('❌ axios is not installed. Installing...');
        console.log('Please run: npm install axios');
        return false;
    }
};

// Run tests if this script is executed directly
if (require.main === module) {
    if (checkDependencies()) {
        runAllTests();
    }
}

module.exports = {
    runAllTests,
    testData,
    makeRequest
};
