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

const BASE_URL = 'http://localhost:5000/api/posts';

// Test data
const testPost = {
    title: 'Test Post Title',
    description: 'This is a test post description with some content to test the post creation functionality.',
    tags: 'test,api,development',
    category: 'general',
    visibility: 'public'
};

let authToken = '';
let createdPostId = '';

// Test user login to get auth token
const testLogin = async () => {
    try {
        console.log('🔐 Testing user login...');
        
        const response = await axios.post('http://localhost:5000/api/auth/login', {
            mobile: '+1234567890', // Use original format
            password: 'password123'
        });
        
        if (response.data.success) {
            authToken = response.data.data.token;
            console.log('✅ Login successful!');
            return true;
        }
    } catch (error) {
        console.log('⚠️  Login failed, will test without authentication');
        console.log('Error:', error.response?.data || error.message);
        console.log('Status:', error.response?.status);
        return false;
    }
};

// Test create post without media
const testCreatePost = async () => {
    try {
        console.log('\n📝 Testing post creation...');
        
        const response = await axios.post(`${BASE_URL}`, testPost, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (response.data.success) {
            createdPostId = response.data.data._id;
            console.log('✅ Post created successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Post creation failed:', error.response?.data || error.message);
        return false;
    }
};

// Test create post with media
const testCreatePostWithMedia = async () => {
    try {
        console.log('\n📸 Testing post creation with media...');
        
        const formData = new FormData();
        formData.append('title', 'Test Post with Media');
        formData.append('description', 'This post includes media files for testing.');
        formData.append('tags', 'test,media,upload');
        formData.append('category', 'general');
        formData.append('visibility', 'public');
        
        // Create a dummy image file for testing
        const testImagePath = path.join(__dirname, '..', 'uploads', 'test-image.txt');
        if (!fs.existsSync(path.dirname(testImagePath))) {
            fs.mkdirSync(path.dirname(testImagePath), { recursive: true });
        }
        fs.writeFileSync(testImagePath, 'This is a test image file');
        
        formData.append('media', fs.createReadStream(testImagePath), {
            filename: 'test-image.txt',
            contentType: 'image/jpeg'
        });
        
        const response = await axios.post(`${BASE_URL}`, formData, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                ...formData.getHeaders()
            }
        });
        
        if (response.data.success) {
            console.log('✅ Post with media created successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Post creation with media failed:', error.response?.data || error.message);
        return false;
    }
};

// Test get all posts
const testGetAllPosts = async () => {
    try {
        console.log('\n📋 Testing get all posts...');
        
        const response = await axios.get(`${BASE_URL}?page=1&limit=5`);
        
        if (response.data.success) {
            console.log('✅ Posts retrieved successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Get posts failed:', error.response?.data || error.message);
        return false;
    }
};

// Test get single post
const testGetPostById = async () => {
    if (!createdPostId) {
        console.log('⚠️  No post ID available for testing');
        return false;
    }
    
    try {
        console.log('\n🔍 Testing get post by ID...');
        
        const response = await axios.get(`${BASE_URL}/${createdPostId}`);
        
        if (response.data.success) {
            console.log('✅ Post retrieved successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Get post by ID failed:', error.response?.data || error.message);
        return false;
    }
};

// Test like post
const testLikePost = async () => {
    if (!createdPostId) {
        console.log('⚠️  No post ID available for testing');
        return false;
    }
    
    try {
        console.log('\n❤️  Testing like post...');
        
        const response = await axios.post(`${BASE_URL}/${createdPostId}/like`, {}, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.data.success) {
            console.log('✅ Post liked successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Like post failed:', error.response?.data || error.message);
        return false;
    }
};

// Test add comment
const testAddComment = async () => {
    if (!createdPostId) {
        console.log('⚠️  No post ID available for testing');
        return false;
    }
    
    try {
        console.log('\n💬 Testing add comment...');
        
        const response = await axios.post(`${BASE_URL}/${createdPostId}/comment`, {
            content: 'This is a test comment for the post.'
        }, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (response.data.success) {
            console.log('✅ Comment added successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Add comment failed:', error.response?.data || error.message);
        return false;
    }
};

// Test share post
const testSharePost = async () => {
    if (!createdPostId) {
        console.log('⚠️  No post ID available for testing');
        return false;
    }
    
    try {
        console.log('\n📤 Testing share post...');
        
        const response = await axios.post(`${BASE_URL}/${createdPostId}/share`, {
            platform: 'facebook'
        }, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (response.data.success) {
            console.log('✅ Post shared successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Share post failed:', error.response?.data || error.message);
        return false;
    }
};

// Test update post
const testUpdatePost = async () => {
    if (!createdPostId) {
        console.log('⚠️  No post ID available for testing');
        return false;
    }
    
    try {
        console.log('\n✏️  Testing update post...');
        
        const response = await axios.put(`${BASE_URL}/${createdPostId}`, {
            title: 'Updated Test Post Title',
            description: 'This is an updated description for the test post.'
        }, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (response.data.success) {
            console.log('✅ Post updated successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Update post failed:', error.response?.data || error.message);
        return false;
    }
};

// Test get post statistics
const testGetPostStats = async () => {
    try {
        console.log('\n📊 Testing get post statistics...');
        
        const response = await axios.get(`${BASE_URL}/stats`);
        
        if (response.data.success) {
            console.log('✅ Post statistics retrieved successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Get post stats failed:', error.response?.data || error.message);
        return false;
    }
};

// Test delete post
const testDeletePost = async () => {
    if (!createdPostId) {
        console.log('⚠️  No post ID available for testing');
        return false;
    }
    
    try {
        console.log('\n🗑️  Testing delete post...');
        
        const response = await axios.delete(`${BASE_URL}/${createdPostId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.data.success) {
            console.log('✅ Post deleted successfully!');
            console.log('📊 Response:', JSON.stringify(response.data, null, 2));
            return true;
        }
    } catch (error) {
        console.error('❌ Delete post failed:', error.response?.data || error.message);
        return false;
    }
};

// Run all tests
const runTests = async () => {
    console.log('🧪 Starting Post API Tests...\n');
    
    // Test login first
    const loginSuccess = await testLogin();
    
    // Test post creation
    const createSuccess = await testCreatePost();
    
    if (createSuccess) {
        // Test other operations
        await testGetAllPosts();
        await testGetPostById();
        await testLikePost();
        await testAddComment();
        await testSharePost();
        await testUpdatePost();
        await testGetPostStats();
        await testDeletePost();
    }
    
    // Test post creation with media
    await testCreatePostWithMedia();
    
    console.log('\n🏁 Post API tests completed!');
};

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