
const compressImage = (file, { maxSize = 1024, quality = 0.8 } = {}) =>
  new Promise((resolve) => {
    if (!file?.type?.startsWith("image/")) {
      resolve(file);
      return;
    }

    const objectUrl = URL.createObjectURL(file);
    const image = new Image();

    const finish = (result) => {
      URL.revokeObjectURL(objectUrl);
      resolve(result);
    };

    image.onerror = () => finish(file);

    image.onload = () => {
      const scale = Math.min(1, maxSize / Math.max(image.width, image.height));
      const canvas = document.createElement("canvas");
      canvas.width = Math.round(image.width * scale);
      canvas.height = Math.round(image.height * scale);

      const context = canvas.getContext("2d");
      if (!context) {
        finish(file);
        return;
      }

      context.drawImage(image, 0, 0, canvas.width, canvas.height);

      canvas.toBlob(
        (blob) => {
          if (!blob || blob.size >= file.size) {
            finish(file);
            return;
          }

          const name = file.name.replace(/\.[^.]+$/, "") || "photo";
          finish(
            new File([blob], `${name}.jpg`, {
              type: "image/jpeg",
              lastModified: Date.now(),
            }),
          );
        },
        "image/jpeg",
        quality,
      );
    };

    image.src = objectUrl;
  });

export default compressImage;
