const cloudinary = require('cloudinary').v2;
const dotenv = require('dotenv');

dotenv.config();

// Cloudinary configuration
cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME || 'dh5fwiqoy',
    api_key: process.env.CLOUDINARY_API_KEY || '316322682753876',
    api_secret: process.env.CLOUDINARY_API_SECRET || 'mHv5t8XaNts6EdUL1bBz_33STXg',
});

// Verify configuration
console.log('Cloudinary Config:', {
    cloud_name: cloudinary.config().cloud_name,
    api_key: cloudinary.config().api_key ? '*** set ***' : 'missing',
    api_secret: cloudinary.config().api_secret ? '*** set ***' : 'missing'
});

/**
 * Upload proof image to Cloudinary
 * @param {string} fileStr - Base64 string or file path of the image
 * @returns {Promise<string>} - Secure URL of the uploaded image
 */
const uploadProof = async (fileStr) => {
    try {
        console.log('Uploading image to Cloudinary with optimization...');

        const uploadResponse = await cloudinary.uploader.upload(fileStr, {
            upload_preset: 'Auction',
            folder: 'proofs',
            resource_type: 'auto',

            // --- IMAGE OPTIMIZATION ---
            // This transformation resizes and compresses the image on upload
            // to ensure fast loading times when viewed.
            transformation: [
                {
                    // Resize to a max width of 1000px, keeping aspect ratio
                    width: 1000,
                    // Resize to a max height of 1000px, keeping aspect ratio
                    height: 1000,
                    // 'limit' ensures it only scales down, never up
                    crop: "limit",
                    // Automatically select good, compressed quality
                    quality: "auto:good",
                    // Automatically select the best format (e.g., WebP, AVIF)
                    fetch_format: "auto"
                }
            ]
            // --- END OF OPTIMIZATION ---
        });

        console.log('Upload successful (optimized):', uploadResponse.secure_url);
        return uploadResponse.secure_url;

    } catch (err) {
        console.error('Cloudinary upload error:', err);
        throw new Error('Image could not be uploaded: ' + err.message);
    }
};

/**
 * Delete image from Cloudinary
 * @param {string} publicId - Public ID of the image to delete
 * @returns {Promise<void>}
 */
const deleteProof = async (publicId) => {
    try {
        const result = await cloudinary.uploader.destroy(publicId);
        console.log('Delete result:', result);
        return result;
    } catch (err) {
        console.error('Cloudinary delete error:', err);
        throw new Error('Image could not be deleted: ' + err.message);
    }
};

/**
 * Extract public ID from Cloudinary URL
 * @param {string} url - Cloudinary URL
 * @returns {string} - Public ID
 */
const getPublicIdFromUrl = (url) => {
    try {
        const matches = url.match(/\/upload\/v\d+\/(.+)\.\w+$/);
        return matches ? matches[1] : null;
    } catch (err) {
        console.error('Error extracting public ID:', err);
        return null;
    }
};

module.exports = {
    uploadProof,
    deleteProof,
    getPublicIdFromUrl
};