const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

// Test configuration
const BASE_URL = 'http://localhost:5500';
const TEST_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY4YzdlZjQxM2M4NjQ3N2IzYjYyNjE3MiIsIm1vYmlsZSI6Ijk1MTU0NDYwODAiLCJpYXQiOjE3NTg2MDkxOTIsImV4cCI6MTc1ODY5NTU5Mn0.3kmZLm2-Jo8gjmBf4L1w7_KG7S_TXpf7vHCln_aKZlM'; // Replace with your actual token
const TEST_POST_ID = '68d15672df66d50676334c90'; // Replace with your actual post ID

async function testPostUpdate() {
    try {
        console.log('🧪 [TEST] Starting post update test...');
        
        // Test 1: Text-only update
        console.log('\n📝 [TEST 1] Testing text-only update...');
        const textUpdateResponse = await axios.put(`${BASE_URL}/api/posts/${TEST_POST_ID}`, {
            title: 'Updated Post Title',
            description: 'This is an updated description',
            tags: 'updated,test,example',
            category: 'general',
            visibility: 'public'
        }, {
            headers: {
                'Authorization': `Bearer ${TEST_TOKEN}`,
                'Content-Type': 'application/json'
            }
        });
        
        console.log('✅ [TEST 1] Text update successful:', textUpdateResponse.data);
        
        // Test 2: Media update (if you have a test image)
        console.log('\n📸 [TEST 2] Testing media update...');
        
        // Create a simple test image file
        const testImagePath = path.join(__dirname, 'test-image.jpg');
        
        // Check if test image exists, if not create a simple one
        if (!fs.existsSync(testImagePath)) {
            console.log('⚠️ [TEST 2] No test image found, creating a simple one...');
            // Create a minimal JPEG file for testing
            const minimalJpeg = Buffer.from([
                0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x48,
                0x00, 0x48, 0x00, 0x00, 0xFF, 0xDB, 0x00, 0x43, 0x00, 0x08, 0x06, 0x06, 0x07, 0x06, 0x05, 0x08,
                0x07, 0x07, 0x07, 0x09, 0x09, 0x08, 0x0A, 0x0C, 0x14, 0x0D, 0x0C, 0x0B, 0x0B, 0x0C, 0x19, 0x12,
                0x13, 0x0F, 0x14, 0x1D, 0x1A, 0x1F, 0x1E, 0x1D, 0x1A, 0x1C, 0x1C, 0x20, 0x24, 0x2E, 0x27, 0x20,
                0x22, 0x2C, 0x23, 0x1C, 0x1C, 0x28, 0x37, 0x29, 0x2C, 0x30, 0x31, 0x34, 0x34, 0x34, 0x1F, 0x27,
                0x39, 0x3D, 0x38, 0x32, 0x3C, 0x2E, 0x33, 0x34, 0x32, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x01,
                0x00, 0x01, 0x01, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xC4, 0x00, 0x14,
                0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x08, 0xFF, 0xC4, 0x00, 0x14, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02,
                0x11, 0x03, 0x11, 0x00, 0x3F, 0x00, 0x8A, 0xFF, 0xD9
            ]);
            fs.writeFileSync(testImagePath, minimalJpeg);
        }
        
        const formData = new FormData();
        formData.append('title', 'Updated Post with Media');
        formData.append('description', 'This post now has media!');
        formData.append('media', fs.createReadStream(testImagePath));
        
        const mediaUpdateResponse = await axios.put(`${BASE_URL}/api/posts/${TEST_POST_ID}`, formData, {
            headers: {
                'Authorization': `Bearer ${TEST_TOKEN}`,
                ...formData.getHeaders()
            }
        });
        
        console.log('✅ [TEST 2] Media update successful:', mediaUpdateResponse.data);
        
        // Test 3: Check if the updated post can be retrieved
        console.log('\n🔍 [TEST 3] Verifying updated post...');
        const getPostResponse = await axios.get(`${BASE_URL}/api/posts/${TEST_POST_ID}`, {
            headers: {
                'Authorization': `Bearer ${TEST_TOKEN}`
            }
        });
        
        console.log('✅ [TEST 3] Post retrieval successful:', getPostResponse.data);
        
        console.log('\n🎉 [TEST] All tests completed successfully!');
        
    } catch (error) {
        console.error('❌ [TEST ERROR] Test failed:', {
            message: error.message,
            status: error.response?.status,
            statusText: error.response?.statusText,
            data: error.response?.data
        });
        
        if (error.response?.status === 404) {
            console.log('\n🔍 [DEBUG] 404 Error Details:');
            console.log('- Check if the post ID exists');
            console.log('- Check if the route is properly configured');
            console.log('- Check if the server is running');
            console.log('- Check if the authentication token is valid');
        }
    }
}

// Run the test
testPostUpdate();
