export interface Dimensions {
  width: number;
  height: number;
}

/**
 * Compute the dimensions an image should be scaled to so that it fits within
 * `maxWidth` × `maxHeight` while keeping its aspect ratio.
 * Images already small enough are left untouched (never enlarged).
 */
export function computeResizedDimensions(
  width: number,
  height: number,
  maxWidth: number,
  maxHeight: number
): Dimensions {
  if (width > maxWidth || height > maxHeight) {
    const ratio = Math.min(maxWidth / width, maxHeight / height);
    return {
      width: Math.round(width * ratio),
      height: Math.round(height * ratio),
    };
  }

  return { width, height };
}

/**
 * Resize an image file to max dimensions using Canvas.
 * Returns a Blob of the resized image.
 */
export function resizeImage(
  file: File,
  maxWidth: number = 300,
  maxHeight: number = 300,
  quality: number = 0.85
): Promise<Blob> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    const reader = new FileReader();

    reader.onload = (e) => {
      img.src = e.target?.result as string;
    };

    img.onload = () => {
      const { width, height } = computeResizedDimensions(
        img.width,
        img.height,
        maxWidth,
        maxHeight
      );

      const canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;

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

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

      canvas.toBlob(
        (blob) => {
          if (blob) {
            resolve(blob);
          } else {
            reject(new Error('Failed to create blob'));
          }
        },
        'image/jpeg',
        quality
      );
    };

    img.onerror = () => reject(new Error('Failed to load image'));
    reader.onerror = () => reject(new Error('Failed to read file'));
    reader.readAsDataURL(file);
  });
}

export const MAX_FILE_SIZE = 1048576; // 1MB
