// src/utils/imageProcessor.ts
import sharp from 'sharp';
import path from 'path';
import fs from 'node:fs/promises'; 
import type { Logger } from 'pino';
import { sanitizeFilename } from './stringUtils';

/**
 * Generates a 64x64 square icon from a source image.
 * @param sourceImagePath The full path to the original image file.
 * @param iconsDirectory The directory where the icon should be saved.
 * @returns A promise that resolves to the filename of the newly created icon.
 * @param logger The request-scoped logger instance, as per ADR-004.
 * @throws An error if the icon generation fails.
 */
export async function generateFlyerIcon(sourceImagePath: string, iconsDirectory: string, logger: Logger): Promise<string> {
  try {
    // 1. Create a new filename, standardizing the extension to .webp for consistency and performance.
    // We sanitize the original filename to remove spaces and special characters, ensuring URL safety.
    // The sourceImagePath is already sanitized by multer, but we apply it here again for robustness
    // in case this function is ever called from a different context.
    const sanitizedBaseName = sanitizeFilename(path.basename(sourceImagePath));
    const originalFileName = path.parse(sanitizedBaseName).name;
    const iconFileName = `icon-${originalFileName}.webp`;
    const iconOutputPath = path.join(iconsDirectory, iconFileName);

    // Ensure the icons subdirectory exists.
    await fs.mkdir(iconsDirectory, { recursive: true });

    // 2. Use sharp to process the image.
    await sharp(sourceImagePath)
      // Use `resize` with a `fit` strategy to prevent distortion.
      // `sharp.fit.cover` will resize to fill 64x64 and crop any excess,
      // ensuring the icon is always a non-distorted square.
      .resize(64, 64, { fit: sharp.fit.cover })
      // 3. Convert the output to WebP format.
      // The `quality` option is a good balance between size and clarity.
      .webp({ quality: 80 })
      .toFile(iconOutputPath);

    logger.info(`Generated 64x64 icon: ${iconFileName}`);
    return iconFileName;
  } catch (error) {
    logger.error({ error, sourceImagePath }, 'Failed to generate flyer icon:');
    throw new Error('Icon generation failed.');
  }
}