/**
 * Normalize inbound Webex file bytes before uploading to ServiceChannel.
 * Converts HEIC/HEIF to JPEG (same as outbound Webex posts).
 */

import convert from 'heic-convert';
import { getContentTypeFromFilename } from '../integrations/serviceChannel/attachments.js';
import { needsJpegConversion, jpegFileName } from './prepareWebexAttachment.js';
import { logger } from './logger.js';

export async function prepareScUpload(buffer, fileName, contentType) {
  const resolvedType = contentType || getContentTypeFromFilename(fileName);

  if (needsJpegConversion(fileName, resolvedType)) {
    const jpegBuffer = Buffer.from(await convert({
      buffer,
      format: 'JPEG',
      quality: 0.92,
    }));

    const outName = jpegFileName(fileName);
    logger('upload:convert', `Converted ${fileName} → ${outName} (${jpegBuffer.length} bytes)`);
    return { buffer: jpegBuffer, fileName: outName, contentType: 'image/jpeg' };
  }

  return {
    buffer,
    fileName,
    contentType: resolvedType === 'application/octet-stream'
      ? getContentTypeFromFilename(fileName)
      : resolvedType,
  };
}
