const cloudinary = require('cloudinary').v2;
const Model = require('../Model'); // Adjust the path according to your project structure
require('dotenv').config();


// Configure Cloudinary

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
    secure: true,
});

// Define the uploadImage function
const uploadImage = async (req, res) => {
    // Assuming the user ID is stored in req.user.id after authentication
    const userId = req.user.id; 
    // console.log("UPLOAD",req.user);
    
    // Check if a file is uploaded
    if (!req.file) {
        return res.status(400).json({ message: 'No file uploaded' });
    }

    // Options for the upload
    const options = {
        resource_type: 'auto',
        public_id: `uploads/${Date.now()}`, // Optional: set a public ID for the uploaded image
        overwrite: true,
    };

    try {
        // Use the buffer to upload
        const stream = require('stream');
        const bufferStream = new stream.PassThrough();
        bufferStream.end(req.file.buffer); // End the stream with the buffer
        
        const result = await new Promise((resolve, reject) => {
            // Upload to Cloudinary
            bufferStream.pipe(cloudinary.uploader.upload_stream(options, (error, result) => {
                if (error) {
                    return reject(error);
                }
                resolve(result);
            }));
        });

        // Save the URL and user ID to the database
        const user = await Model.User.findById(userId);
        
        // const newImageRecord = await Model.ProfileLogo.create({
        //     imageUrl: result.secure_url, // URL from Cloudinary
        //     userId: userId, // The user ID from the request
        // });

        if (!user) {
            throw new Error('User not found');
        }
        
        
        
        user.imageUrl = result.secure_url;
        await user.save();
        console.log("image url is ",user.imageUrl);
        
        return res.status(201).json({
            status: true,
            message: 'Image uploaded and saved successfully',
            imageUrl: user.imageUrl, // URL from Cloudinary
        });
    } catch (error) {
        console.error(error);
        return res.status(500).json({ message: 'Upload failed', error });
    }
};

const getProfileLogo = async (req, res) => {
    const role  = req.user.role;
    let userId = req.user.id
    // const useri = req.user.AdminId;
    // console.log("IN GET PROFILE LOGO",userId);
    
    try {
         

        if (role !== 'user' && role !== 'admin') {
            return res.status(404).json({
                status: false,
                message: 'Not allowed',
            });
        }
        
         if(role === 'user') {
            userId= req.user.AdminId;
         }
        

        // If the user is an admin, fetch the profile logo directly using userId
        const user = await Model.User.findById(userId);

        if (!user.imageUrl) {
            return res.status(404).json({
                status: false,
                message: 'Profile logo not found for the provided user or admin ID'
            });
        }
//   const profileLogo=user.imageUrl;
        // Return the profile logo details
        return res.status(200).json({
            status: true,
            message: 'Profile logo retrieved successfully',
            // profileLogo,
            data:{imageUrl: user.imageUrl}
        });
    } catch (error) {
        console.error("Error fetching profile logo:", error);
        return res.status(500).json({
            status: false,
            message: 'Failed to retrieve profile logo',
            error
        });
    }
};

module.exports = {
    uploadImage,getProfileLogo
};
