export interface ConvertToWebPOptions {
  maxWidth?: number;
  maxHeight?: number;
  quality?: number; // optional extension
}

export function convertToWebP(
  file: File,
  { maxWidth, maxHeight, quality }: ConvertToWebPOptions = {},
): Promise<Blob> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = (event) => {
      const result = event.target?.result;
      if (typeof result !== "string") {
        reject(new Error("Failed to read file"));
        return;
      }

      const image = new Image();
      image.src = result;

      image.onload = () => {
        const canvas = document.createElement("canvas");

        let width = image.width;
        let height = image.height;
        const aspectRatio = width / height;

        if (maxWidth !== undefined && width > maxWidth) {
          width = maxWidth;
          height = width / aspectRatio;
        }

        if (maxHeight !== undefined && height > maxHeight) {
          height = maxHeight;
          width = height * aspectRatio;
        }

        canvas.width = width;
        canvas.height = height;

        const ctx = canvas.getContext("2d");
        if (!ctx) {
          reject(new Error("Canvas context not available"));
          return;
        }

        ctx.drawImage(image, 0, 0, width, height);

        canvas.toBlob(
          (blob) => {
            if (!blob) {
              reject(new Error("Blob conversion failed"));
              return;
            }
            resolve(blob);
          },
          "image/webp",
          quality,
        );
      };

      image.onerror = () => reject(new Error("Image load failed"));
    };

    reader.onerror = () => reject(new Error("FileReader failed"));
    reader.readAsDataURL(file);
  });
}
