/**
 * Credential Image/Logo Management for Entra VerifiedID
 * Handles image conversion and validation for credential display
 */

export interface CredentialImageConfig {
  logoUri?: string;
  backgroundColor?: string;
  textColor?: string;
  description?: string;
}

export interface ImageFormat {
  format: 'svg' | 'png' | 'jpg' | 'jpeg' | 'bmp';
  data: string | Buffer;
  mimeType: string;
}

/**
 * Supported image formats for Entra VerifiedID
 * Note: Entra VerifiedID officially supports PNG, JPG, BMP
 * SVG may work but PNG is recommended for compatibility
 */
export const SUPPORTED_FORMATS = ['png', 'jpg', 'jpeg', 'bmp', 'svg'] as const;
export type SupportedFormat = typeof SUPPORTED_FORMATS[number];

/**
 * Validate image format
 */
export function validateImageFormat(format: string): format is SupportedFormat {
  return SUPPORTED_FORMATS.includes(format.toLowerCase() as SupportedFormat);
}

/**
 * Get MIME type for image format
 */
export function getImageMimeType(format: SupportedFormat): string {
  const mimeTypes: Record<SupportedFormat, string> = {
    svg: 'image/svg+xml',
    png: 'image/png',
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    bmp: 'image/bmp',
  };
  return mimeTypes[format] || 'image/png';
}

/**
 * Convert SVG to PNG (if needed for Entra compatibility)
 * Note: This requires additional dependencies like sharp or svg2png
 */
export async function convertSvgToPng(
  svgData: string | Buffer,
  width: number = 200,
  height: number = 200
): Promise<Buffer> {
  // Check if sharp is available (optional dependency)
  try {
    // eslint-disable-next-line @typescript-eslint/no-require-imports
    const sharp = require('sharp');
    
    const svgBuffer = typeof svgData === 'string' ? Buffer.from(svgData) : svgData;
    return await sharp(svgBuffer)
      .resize(width, height)
      .png()
      .toBuffer();
  } catch (error) {
    // If sharp is not available, return original SVG
    // Note: Entra may accept SVG, but PNG is recommended
    console.warn('sharp not available, using SVG directly (may not be supported by Entra)');
    return typeof svgData === 'string' ? Buffer.from(svgData) : svgData;
  }
}

/**
 * Prepare image for Entra VerifiedID
 * Converts SVG to PNG if needed, validates format
 */
export async function prepareCredentialImage(
  imageData: string | Buffer,
  format?: SupportedFormat
): Promise<{
  data: Buffer;
  mimeType: string;
  format: SupportedFormat;
}> {
  let imageBuffer: Buffer;
  let detectedFormat: SupportedFormat;
  let mimeType: string;

  // Detect format if not provided
  if (!format) {
    if (typeof imageData === 'string') {
      // Check if it's a data URL
      if (imageData.startsWith('data:')) {
        const match = imageData.match(/data:image\/([^;]+)/);
        detectedFormat = (match?.[1]?.toLowerCase() || 'png') as SupportedFormat;
      } else if (imageData.trim().startsWith('<svg')) {
        detectedFormat = 'svg';
      } else {
        detectedFormat = 'png'; // Default
      }
    } else {
      // Try to detect from buffer (basic check)
      const header = imageData.toString('hex', 0, 4);
      if (header.startsWith('89504e47')) {
        detectedFormat = 'png';
      } else if (header.startsWith('ffd8ff')) {
        detectedFormat = 'jpg';
      } else if (header.startsWith('424d')) {
        detectedFormat = 'bmp';
      } else {
        detectedFormat = 'png'; // Default
      }
    }
  } else {
    detectedFormat = format;
  }

  // Convert to buffer if string
  if (typeof imageData === 'string') {
    if (imageData.startsWith('data:')) {
      // Extract base64 data
      const base64Data = imageData.split(',')[1];
      imageBuffer = Buffer.from(base64Data, 'base64');
    } else {
      imageBuffer = Buffer.from(imageData);
    }
  } else {
    imageBuffer = imageData;
  }

  // Convert SVG to PNG for Entra compatibility
  if (detectedFormat === 'svg') {
    try {
      imageBuffer = await convertSvgToPng(imageBuffer);
      detectedFormat = 'png';
      mimeType = 'image/png';
    } catch (error) {
      console.warn('SVG to PNG conversion failed, using SVG (may not be supported)', error);
      mimeType = 'image/svg+xml';
    }
  } else {
    mimeType = getImageMimeType(detectedFormat);
  }

  // Validate format
  if (!validateImageFormat(detectedFormat)) {
    throw new Error(`Unsupported image format: ${detectedFormat}. Supported: ${SUPPORTED_FORMATS.join(', ')}`);
  }

  return {
    data: imageBuffer,
    mimeType,
    format: detectedFormat,
  };
}

/**
 * Create data URL from image
 */
export function createImageDataUrl(imageData: Buffer, mimeType: string): string {
  const base64 = imageData.toString('base64');
  return `data:${mimeType};base64,${base64}`;
}

/**
 * Get recommended image specifications for Entra VerifiedID
 */
export function getRecommendedImageSpecs(): {
  format: 'png' | 'jpg';
  width: number;
  height: number;
  maxSizeKB: number;
} {
  return {
    format: 'png', // Recommended format
    width: 200,
    height: 200,
    maxSizeKB: 100, // Max 100KB recommended
  };
}

