const axios = require('axios');

const BASE_URL = 'http://192.168.29.136:5500/api/users';

async function testUserRegistration() {
    console.log('🧪 Testing User Registration...\n');
    
    try {
        // Test 1: Register a new user
        console.log('📝 Test 1: Register a new user');
        const registerData = {
            name: 'Test User',
            mobile: '9876543210',
            password: 'testpassword123',
            email: 'test@example.com',
            dob: '15-08-1995',
            gender: 'Male',
            emailId: 'test@example.com',
            bloodGroup: 'O+',
            pincodeNative: '110001',
            state: 'Delhi',
            district: 'New Delhi',
            nativePlace: 'Delhi',
            nameMeaning: 'Test name meaning'
        };
        
        const registerResponse = await axios.post(`${BASE_URL}/register`, registerData);
        console.log('✅ Registration Response:', registerResponse.data);
        console.log('');
        
        return registerResponse.data.data.userId;
        
    } catch (error) {
        console.error('❌ Registration Test Failed:', error.response?.data || error.message);
        return null;
    }
}

async function testUserLogin(mobile, password) {
    console.log('🧪 Testing User Login...\n');
    
    try {
        // Test 1: Login with correct credentials
        console.log('📝 Test 1: Login with correct credentials');
        const loginData = {
            mobile: mobile,
            password: password
        };
        
        const loginResponse = await axios.post(`${BASE_URL}/login`, loginData);
        console.log('✅ Login Response:', loginResponse.data);
        console.log('');
        
        return loginResponse.data.data.token;
        
    } catch (error) {
        console.error('❌ Login Test Failed:', error.response?.data || error.message);
        return null;
    }
}

async function testOTPVerification(mobile, otp) {
    console.log('🧪 Testing OTP Verification...\n');
    
    try {
        // Test 1: Verify OTP
        console.log('📝 Test 1: Verify OTP');
        const otpData = {
            mobile: mobile,
            otp: otp
        };
        
        const otpResponse = await axios.post(`${BASE_URL}/verify-otp`, otpData);
        console.log('✅ OTP Verification Response:', otpResponse.data);
        console.log('');
        
        return otpResponse.data.data.token;
        
    } catch (error) {
        console.error('❌ OTP Verification Test Failed:', error.response?.data || error.message);
        return null;
    }
}

async function testValidationErrors() {
    console.log('🧪 Testing Validation Errors...\n');
    
    try {
        // Test 1: Missing required fields
        console.log('📝 Test 1: Missing required fields');
        try {
            await axios.post(`${BASE_URL}/register`, {
                name: 'Test User'
                // Missing mobile and password
            });
        } catch (error) {
            console.log('✅ Expected validation error:', error.response?.data);
        }
        console.log('');
        
        // Test 2: Invalid date format
        console.log('📝 Test 2: Invalid date format');
        try {
            await axios.post(`${BASE_URL}/register`, {
                name: 'Test User',
                mobile: '9876543211',
                password: 'testpassword123',
                dob: 'invalid-date'
            });
        } catch (error) {
            console.log('✅ Expected validation error:', error.response?.data);
        }
        console.log('');
        
        // Test 3: Login with wrong password
        console.log('📝 Test 3: Login with wrong password');
        try {
            await axios.post(`${BASE_URL}/login`, {
                mobile: '9876543210',
                password: 'wrongpassword'
            });
        } catch (error) {
            console.log('✅ Expected validation error:', error.response?.data);
        }
        console.log('');
        
    } catch (error) {
        console.error('❌ Validation Test Failed:', error.response?.data || error.message);
    }
}

async function testUserAboutWithToken(token) {
    console.log('🧪 Testing User About with Token...\n');
    
    try {
        // Test 1: Get user about
        console.log('📝 Test 1: Get user about');
        const getAboutResponse = await axios.get(`${BASE_URL}/about/68d2b0eb2a0740535e9c35c4`);
        console.log('✅ Get About Response:', getAboutResponse.data);
        console.log('');
        
        // Test 2: Update user about with token
        console.log('📝 Test 2: Update user about with token');
        const updateAboutResponse = await axios.put(`${BASE_URL}/about/68d2b0eb2a0740535e9c35c4`, {
            about: 'This is a test about section updated with authentication.'
        }, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
        console.log('✅ Update About Response:', updateAboutResponse.data);
        console.log('');
        
    } catch (error) {
        console.error('❌ About API Test Failed:', error.response?.data || error.message);
    }
}

async function runAllTests() {
    console.log('🚀 Starting User Registration and Login Tests...\n');
    console.log('='.repeat(60));
    
    // Test registration
    const userId = await testUserRegistration();
    console.log('='.repeat(60));
    
    // Test login (this will fail because user is not verified)
    const token = await testUserLogin('9876543210', 'testpassword123');
    console.log('='.repeat(60));
    
    // Test OTP verification (you'll need to check the server logs for the OTP)
    console.log('📱 Note: Check server logs for the OTP code to test OTP verification');
    console.log('='.repeat(60));
    
    // Test validation errors
    await testValidationErrors();
    console.log('='.repeat(60));
    
    // Test about API with existing token
    const existingToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY4ZDJiMGViMmEwNzQwNTM1ZTljMzVjNCIsImlhdCI6MTczNzU0NzQ4MCwiZXhwIjoxNzM4MTUyMjgwfQ.8QZ8QZ8QZ8QZ8QZ8QZ8QZ8QZ8QZ8QZ8QZ8QZ8QZ';
    await testUserAboutWithToken(existingToken);
    console.log('='.repeat(60));
    
    console.log('✅ All tests completed!');
    console.log('📝 Note: To complete the registration flow, you need to:');
    console.log('   1. Check server logs for the OTP code');
    console.log('   2. Use the OTP to verify the user');
    console.log('   3. Then test login with the verified user');
}

// Run the tests
runAllTests().catch(console.error);
