const ImageKit = require("imagekit");
const dotenv = require("dotenv");
const multer = require("multer");
dotenv.config();

const imageKitCredentials = {
    publicKey: process.env.IMAGE_KIT_PUBLIC_KEY,
    privateKey: process.env.IMAGE_KIT_PRIVATE_KEY,
    urlEndpoint: process.env.IMAGE_KIT_URL_END_POINT,
};

const imageKit = new ImageKit(imageKitCredentials);

exports.uploadToImageKit = async (file) => {
    return new Promise((resolve, reject) => {
        imageKit.upload(
            {
                file: file.buffer, 
                fileName: file.originalname,
                folder: "/uploads/",
            },
            (error, result) => {
                if (error) {
                    return reject(error);
                }
                resolve(result);
            }
        );
    });
};


exports.delete = (req, res) => {
    const { url } = req.body;
    if (!url) {
        return res.status(400).json({ error: "URL is required" });
    }

    const urlSlices = url.split("/");
    const fileId = decodeURIComponent(urlSlices.pop());

    imageKit.deleteFile(fileId, (error, result) => {
        if (error) {
            console.error("Error deleting file:", error);
            return res.status(500).json({ error: error.message });
        }
        console.log("File deleted successfully.");
        res.status(200).json({ message: "File deleted successfully" });
    });
};