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

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

// Sample personal details data
const samplePersonalDetails = {
    fullName: 'John Doe',
    gender: 'Male',
    emailId: 'john.doe@example.com',
    bloodGroup: 'O+',
    pincodeNative: '110001',
    state: 'Delhi',
    district: 'Central Delhi',
    nativePlace: 'New Delhi',
    occupation: 'Employee',
    nameMeaning: 'John means God is gracious, and Doe is a common surname'
};

// Helper function to make authenticated requests
const makeAuthenticatedRequest = async (method, endpoint, data = null, token = null) => {
    try {
        const config = {
            method,
            url: `${BASE_URL}${endpoint}`,
            headers: {
                'Content-Type': 'application/json'
            }
        };
        
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        
        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 
        };
    }
};

// Get authentication token first
const getAuthToken = async () => {
    console.log('🔐 Getting authentication token...');
    
    const loginResult = await makeAuthenticatedRequest('POST', '/auth/login', {
        mobile: '+1234567890',
        password: 'password123'
    });
    
    if (loginResult.success) {
        console.log('✅ Authentication successful');
        return loginResult.data.data.token;
    } else {
        console.log('❌ Authentication failed:', loginResult.error);
        return null;
    }
};

// Test functions
const testCreatePersonalDetails = async (token) => {
    console.log('\n📝 Testing: Create Personal Details');
    console.log('=' .repeat(50));
    
    const result = await makeAuthenticatedRequest('POST', '/personal-details', samplePersonalDetails, token);
    
    if (result.success) {
        console.log('✅ Personal details created successfully!');
        console.log('👤 Full Name:', result.data.data.personalDetails.fullName);
        console.log('📧 Email:', result.data.data.personalDetails.emailId);
        console.log('🩸 Blood Group:', result.data.data.personalDetails.bloodGroup);
        console.log('📍 Location:', `${result.data.data.personalDetails.nativePlace}, ${result.data.data.personalDetails.district}, ${result.data.data.personalDetails.state}`);
        console.log('💼 Occupation:', result.data.data.personalDetails.occupation);
        console.log('📊 Completion:', `${result.data.data.completionPercentage}%`);
        console.log('✅ Is Complete:', result.data.data.isCompleted);
    } else {
        console.log('❌ Failed to create personal details:', result.error);
    }
};

const testGetPersonalDetails = async (token) => {
    console.log('\n👤 Testing: Get Personal Details');
    console.log('=' .repeat(50));
    
    const result = await makeAuthenticatedRequest('GET', '/personal-details', null, token);
    
    if (result.success) {
        console.log('✅ Personal details retrieved successfully!');
        const details = result.data.data.personalDetails;
        console.log('👤 Full Name:', details.fullName);
        console.log('⚧ Gender:', details.gender);
        console.log('📧 Email:', details.emailId);
        console.log('🩸 Blood Group:', details.bloodGroup);
        console.log('📮 Pincode:', details.pincodeNative);
        console.log('📍 Native Place:', details.nativePlace);
        console.log('💼 Occupation:', details.occupation);
        if (details.nameMeaning) {
            console.log('📖 Name Meaning:', details.nameMeaning);
        }
    } else {
        console.log('❌ Failed to get personal details:', result.error);
    }
};

const testGetProfileCompletion = async (token) => {
    console.log('\n📊 Testing: Get Profile Completion');
    console.log('=' .repeat(50));
    
    const result = await makeAuthenticatedRequest('GET', '/personal-details/completion', null, token);
    
    if (result.success) {
        console.log('✅ Profile completion retrieved successfully!');
        console.log('📊 Completion Percentage:', `${result.data.data.completionPercentage}%`);
        console.log('✅ Is Complete:', result.data.data.isCompleted);
        if (result.data.data.missingFields && result.data.data.missingFields.length > 0) {
            console.log('❌ Missing Fields:', result.data.data.missingFields.join(', '));
        } else {
            console.log('✅ All required fields completed!');
        }
    } else {
        console.log('❌ Failed to get profile completion:', result.error);
    }
};

const testUpdatePersonalDetails = async (token) => {
    console.log('\n✏️ Testing: Update Personal Details');
    console.log('=' .repeat(50));
    
    const updateData = {
        occupation: 'Business',
        nameMeaning: 'Updated: John means God is gracious, and Doe represents a common family name'
    };
    
    const result = await makeAuthenticatedRequest('PUT', '/personal-details', updateData, token);
    
    if (result.success) {
        console.log('✅ Personal details updated successfully!');
        console.log('💼 New Occupation:', result.data.data.personalDetails.occupation);
        console.log('📖 Updated Name Meaning:', result.data.data.personalDetails.nameMeaning);
        console.log('📊 Completion:', `${result.data.data.completionPercentage}%`);
    } else {
        console.log('❌ Failed to update personal details:', result.error);
    }
};

const testValidationErrors = async (token) => {
    console.log('\n🚫 Testing: Validation Errors');
    console.log('=' .repeat(50));
    
    const invalidData = {
        fullName: 'A', // Too short
        gender: 'Invalid', // Invalid gender
        emailId: 'invalid-email', // Invalid email
        bloodGroup: 'Invalid', // Invalid blood group
        pincodeNative: '123', // Invalid pincode
        occupation: 'Invalid' // Invalid occupation
    };
    
    const result = await makeAuthenticatedRequest('POST', '/personal-details', invalidData, token);
    
    if (!result.success) {
        console.log('✅ Validation working correctly - errors caught:');
        if (result.error.errors) {
            result.error.errors.forEach((error, index) => {
                console.log(`   ${index + 1}. ${error.msg}`);
            });
        }
    } else {
        console.log('❌ Validation should have failed but didn\'t');
    }
};

// Main test runner
const runPersonalDetailsTests = async () => {
    console.log('🚀 Starting Personal Details API Tests');
    console.log('=' .repeat(80));
    console.log(`🌐 Base URL: ${BASE_URL}`);
    console.log(`⏰ Test Time: ${new Date().toLocaleString()}`);
    
    try {
        // Get authentication token
        const token = await getAuthToken();
        
        if (!token) {
            console.log('❌ Cannot proceed without authentication token');
            return;
        }
        
        // Run all tests
        await testCreatePersonalDetails(token);
        await testGetPersonalDetails(token);
        await testGetProfileCompletion(token);
        await testUpdatePersonalDetails(token);
        await testValidationErrors(token);
        
        console.log('\n🎉 All Personal Details tests completed!');
        console.log('=' .repeat(80));
        
    } catch (error) {
        console.error('❌ Test runner error:', error.message);
    }
};

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

module.exports = {
    runPersonalDetailsTests,
    samplePersonalDetails,
    makeAuthenticatedRequest
};
