const ImageKit = require("imagekit");
const dotenv = require("dotenv");
const fs = require("fs");
const path = require("path");
const Image = require("../models/Image");
dotenv.config();

// dead item


const imagekit = new ImageKit({
    publicKey: process.env.IMAGE_KIT_PUBLIC_KEY,
    privateKey: process.env.IMAGE_KIT_PRIVATE_KEY,
    urlEndpoint: process.env.IMAGE_KIT_URL_END_POINT,
});

exports.uploadSingle = async (req, res) => {
    try {
        const file = req.image;
        const filePath = path.join(__dirname, '../public/images', file.filename);

        // Read file from local storage
        fs.readFile(filePath, (err, data) => {
            if (err) {
                console.error("Error reading file:", err);
                return res.status(500).json({ success: false, error: "Failed to read file" });
            }

            // Upload to ImageKit
            imagekit.upload({
                file: data, // File data
                fileName: file.originalname, // File name
            })
            .then(response => {
                console.log('Response after uploading to ImageKit:', response);
                storeInDataBase(response);

                // Delete the local file after successful upload
                fs.unlink(filePath, (err) => {
                    if (err) {
                        console.error("Error deleting local file:", err);
                        return res.status(500).json({ success: false, error: "Failed to delete local file" });
                    }
                    res.json({ success: true, url: response.url });
                });
            })
            .catch(error => {
                console.error("Error uploading image to ImageKit.io:", error);
                res.status(500).json({ success: false, error: "Failed to upload image" });
            });
        });
    } catch (error) {
        console.error("Error in uploadSingle:", error);
        res.status(500).json({ success: false, error: "Internal Server Error" });
    }
};


exports.uploadSingle2 = async (req, res) => {
    try {
        const file = req.file; // ✅ Correct way to access the uploaded file
        if (!file) {
            return res.status(400).json({ success: false, error: "No file uploaded" });
        }

        const filePath = path.join(__dirname, '../public/images', file.filename);

        // Read file from local storage
        fs.readFile(filePath, (err, data) => {
            if (err) {
                console.error("Error reading file:", err);
                return res.status(500).json({ success: false, error: "Failed to read file" });
            }

            // Upload to ImageKit
            imagekit.upload({
                file: data,
                fileName: file.originalname,
            })
            .then(response => {
                console.log('Response after uploading to ImageKit:', response);

                // Delete local file after successful upload
                fs.unlink(filePath, (err) => {
                    if (err) {
                        console.error("Error deleting local file:", err);
                        return res.status(500).json({ success: false, error: "Failed to delete local file" });
                    }
                    res.json({ success: true, url: response.url });
                });
            })
            .catch(error => {
                console.error("Error uploading image to ImageKit.io:", error);
                res.status(500).json({ success: false, error: "Failed to upload image" });
            });
        });
    } catch (error) {
        console.error("Error in uploadSingle:", error);
        res.status(500).json({ success: false, error: "Internal Server Error" });
    }
};


exports.uploadMultiple = async (req, res) => {
    try {
        const files = req.files;
        const uploadPromises = files.map(file => {
            const filePath = path.join(__dirname, '../public/images', file.filename);
            return new Promise((resolve, reject) => {
                // Read file from local storage
                fs.readFile(filePath, (err, data) => {
                    if (err) {
                        console.error("Error reading file:", err);
                        reject("Failed to read file");
                        return;
                    }

                    // Upload to ImageKit
                    imagekit.upload({
                        file: data, // File data
                        fileName: file.originalname, // File name
                    })
                    .then(response => {
                        console.log('Response after uploading to ImageKit:', response);
                        storeInDataBase(response)

                        // Delete the local file after successful upload
                        fs.unlink(filePath, (err) => {
                            if (err) {
                                console.error("Error deleting local file:", err);
                                reject("Failed to delete local file");
                                return;
                            }
                            resolve(response.url);
                        });
                    })
                    .catch(error => {
                        console.error("Error uploading image to ImageKit.io:", error);
                        reject("Failed to upload image");
                    });
                });
            });
        });

        const urls = await Promise.all(uploadPromises);
        res.json({ success: true, urls });

    } catch (error) {
        console.error("Error in uploadMultiple:", error);
        res.status(500).json({ success: false, error: "Internal Server Error" });
    }
};
async function storeInDataBase(imageResponse){
    try{
        const {fileId,url} = imageResponse;
        const newImage = await Image.create({
            url,
            imageId:fileId
        });
    }catch(error){
        console.log('There was an error saving image to database ===>>> ',error);
    }
}

