import { defineEventHandler, readMultipartFormData } from "h3";
import { promises as fs } from "fs";
import sharp from "sharp";

export default defineEventHandler(async (event) => {
  const files = await readMultipartFormData(event);

  if (!files || files.length === 0) {
    return { error: "No files uploaded" };
  }

  const uploadedFile = files[0];
  const fileName = `cropped-${Date.now()}.png`;
  const filePath = `./public/uploads/${fileName}`;

  // Save the cropped image
  await fs.writeFile(filePath, uploadedFile.data);

  // Optionally resize the image
  const resizedFilePath = `./public/uploads/resized-${fileName}`;
  await sharp(uploadedFile.data)
    .resize(300, 300) // Adjust dimensions as needed
    .toFile(resizedFilePath);

  return {
    message: "File uploaded successfully",
    originalFile: `/uploads/${fileName}`,
    resizedFile: `/uploads/resized-${fileName}`,
  };
});
