/**
 * Normalize attachment bytes/filenames for Webex Messages API uploads.
 *
 * Webex supports jpeg/png/gif/bmp and common office/pdf types — not HEIC/HEIF.
 * @see https://developer.webex.com/docs/basics#message-attachments
 */

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

const WEBEX_NATIVE_EXT = /\.(jpe?g|png|gif|bmp|pdf|docx?|xls|pptx?)$/i;
const CONVERT_TO_JPEG_EXT = /\.(heic|heif)$/i;

export function isWebexNativeUpload(fileName) {
  return WEBEX_NATIVE_EXT.test(String(fileName || ''));
}

export function needsJpegConversion(fileName, contentType = '') {
  const name = String(fileName || '');
  if (CONVERT_TO_JPEG_EXT.test(name)) return true;
  const ct = String(contentType || '').toLowerCase();
  return ct === 'image/heic' || ct === 'image/heif' || ct === 'image/heif-sequence';
}

export function jpegFileName(originalName) {
  const base = String(originalName || 'attachment').replace(/\.(heic|heif)$/i, '');
  return `${base}.jpg`;
}

/**
 * Prepare a downloaded attachment for Webex upload.
 * Converts HEIC/HEIF to JPEG when needed.
 */
export async function prepareWebexUpload(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('attachments:convert', `Converted ${fileName} → ${outName} (${jpegBuffer.length} bytes)`);
    return { buffer: jpegBuffer, fileName: outName, contentType: 'image/jpeg' };
  }

  if (resolvedType === 'application/octet-stream') {
    throw new Error(`Unsupported or unknown MIME type for Webex: ${fileName}`);
  }

  return { buffer, fileName, contentType: resolvedType };
}
