const Minio = require('minio');

const minioClient = new Minio.Client({
  endPoint: process.env.MINIO_ENDPOINT.replace(/^https?:\/\//, ''),
  port: parseInt(process.env.MINIO_PORT),
  useSSL: false,
  accessKey: process.env.MINIO_ACCESS_KEY,
  secretKey: process.env.MINIO_SECRET_KEY,
  pathStyle: true,
  transport: {
    agent: false,
  }
});

const uploadFile = async (file, folderPath) => {
  const fileName = `${Date.now()}-${file.filename}`;
  const filePath = `${folderPath}/${fileName}`;
  await minioClient.putObject(process.env.MINIO_BUCKET, filePath, file.file);
  return filePath;
};

const deleteFile = async (filePath) => {
  await minioClient.removeObject(process.env.MINIO_BUCKET, filePath);
};

const getFile = async (filePath) => {
  const file = await minioClient.getObject(process.env.MINIO_BUCKET, filePath);
  return file;
};

const listFiles = async (folderPath) => {
  const files = await minioClient.listObjects(process.env.MINIO_BUCKET, folderPath);
  return files;
};

const getFileUrl = async (filePath) => {
  const url = await minioClient.presignedUrl('GET', process.env.MINIO_BUCKET, filePath);
  return url;
};



module.exports = { uploadFile, deleteFile, getFile, listFiles, getFileUrl };
