const GalleryImage = require('../../models/imageGallery');
const axios = require('axios');
const FormData = require('form-data'); // Import form-data for Node.js

const saveGalleryImage = async (req, res) => {
    try {
        const { childId, gameName, gameID, screenShot } = req.body;

        // Validate base64 format
        const isValidBase64 = validateBase64(screenShot);
        if (!isValidBase64) {
            return res.status(400).json({ error: 'Invalid base64 image data' });
        }

        // Extract image details
        const imageData = extractImageDataFromBase64(screenShot);
        const contentType = imageData.contentType || 'image/jpeg'; // Default to JPEG

        // Convert base64 to buffer
        const buffer = Buffer.from(screenShot.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''), 'base64');

        // Create FormData
        const formData = new FormData();
        formData.append('file1', buffer, { filename: 'screenshot.jpg', contentType });
        formData.append('folder', 'gameGallery');
        formData.append('bucket', 'polly-bs');

        // Upload image to external API using axios
        const uploadResponse = await axios.post(
            'https://preschool-curriculum.in/api/one/v1/file/upload',
            formData,
            {
                headers: {
                    ...formData.getHeaders(), // Add form-data headers like Content-Type boundary
                    // Add any necessary authentication headers if required
                },
            }
        );

        if (uploadResponse.status !== 200) {
            throw new Error('Image upload failed: ' + uploadResponse.statusText);
        }

         
        // Extract and store the uploaded image URL from the response
        const screenshotUrl = uploadResponse.data.urls[0];

        // Create and save gallery image data
        const galleryImageData = new GalleryImage({
            childId,
            gameName,
            gameID,
            screenshotUrl,
            message: 'Image received',
        });
        await galleryImageData.save();

        return res.status(200).json(galleryImageData);
    } catch (error) {
        console.error('Error:', error.message);
        return res.status(500).json({ error: 'Something went wrong' });
    }
};

// Validate base64 image
function validateBase64(base64String) {
    const regex = /^data:image\/(png|jpg|jpeg);base64,/;
    return regex.test(base64String);
}

// Extract image data (like content type) from base64 string
function extractImageDataFromBase64(base64String) {
    const matches = base64String.match(/^data:image\/(png|jpg|jpeg);base64,/);
    return {
        contentType: matches ? `image/${matches[1]}` : 'image/jpeg',
    };
}

module.exports = saveGalleryImage;
