import { v2 as cloudinary } from 'cloudinary';

cloudinary.config({
  cloud_name: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,
  api_key: process.env.NEXT_PUBLIC_CLOUDINARY_API_KEY,
  api_secret: process.env.NEXT_PUBLIC_CLOUDINARY_API_SECRET,
});

/**
 * Uploads a buffer to Cloudinary into a specified project subfolder.
 * @param buffer - Image buffer
 * @param projectSlug - The slug of the project to create a subfolder for
 */
export async function uploadBuffer(buffer: Buffer, projectSlug: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const uploadStream = cloudinary.uploader.upload_stream(
      { 
        folder: `aycanur-projects/${projectSlug}`,
        use_filename: true,
        unique_filename: true
      },
      (error, result) => {
        if (result) resolve(result.secure_url);
        else reject(error);
      }
    );
    uploadStream.end(buffer);
  });
}

export default cloudinary;
