import { FastifyReply, FastifyRequest } from "fastify";
import { v4 as uuid } from "uuid";
import { bucketName } from "../../utils/consts";
import { minioClient } from "../../utils/minio";
import { MinioDeleteFileSchema, MinioDocumentSchema } from "./schema";

export async function uploadFile(
  req: FastifyRequest<{ Body: MinioDocumentSchema }>,
  reply: FastifyReply
) {
  const data = req.body;
  const buffer = await data.document.toBuffer();
  const ext = data.document.filename.split(".").pop();
  const fileName = "folder/" + uuid() + "." + ext;
  await minioClient.putObject(bucketName, fileName, buffer);
  return reply.code(200).send({ document: fileName });
}

export async function deleteFile(
  req: FastifyRequest<{
    Body: MinioDeleteFileSchema;
  }>,
  reply: FastifyReply
) {
  const data = req.body;
  await minioClient.removeObject(bucketName, data.path);
  return reply.code(200).send({});
}

// export async function minio(
//   req: FastifyRequest<{
//     Body: MinioSchema;
//   }>,
//   reply: FastifyReply
// ) {
//   const data = req.body;
//   const fileName = "folder/" + data.file.filename;

//   const buffer = await data.file.toBuffer();
//   const res = await minioClient.putObject(bucketName, fileName, buffer);
//   // await minioClient.removeObject(bucketName, fileName);
//   console.log(res);
//   return reply.code(200).send({});
// }

// export async function minioGet(req: FastifyRequest, reply: FastifyReply) {
//   let size = 0;
// console.log(size);
// const dataStream = await minioClient.getObject(
//   bucketName,
//   "folder/IMG-20240508-WA0011.jpg"
// );
// dataStream.on("data", function (chunk) {
//   size += chunk.length;
// });
// dataStream.on("end", function () {
//   console.log("End. Total size = " + size);
// });
// dataStream.on("error", function (err) {
//   console.log(err);
// });
// const url = await getPresignedUrl("image.jpg");
// return reply.code(200).send(url);
// }
