import { BaseDecoder } from './base.decoder.js';
import { FacturXDecoder } from './facturx.decoder.js';
import { XInvoiceDecoder } from './xinvoice.decoder.js';

/**
 * Factory class for creating the appropriate decoder based on XML format.
 * Analyzes XML content and returns the best decoder for the given format.
 */
export class DecoderFactory {
  /**
   * Creates a decoder for the given XML content
   */
  public static createDecoder(xmlString: string): BaseDecoder {
    if (!xmlString) {
      throw new Error('No XML string provided for decoder selection');
    }
    
    const format = DecoderFactory.detectFormat(xmlString);
    
    switch (format) {
      case 'XInvoice/UBL':
        return new XInvoiceDecoder(xmlString);
        
      case 'FacturX/ZUGFeRD':
      default:
        // Default to FacturX/ZUGFeRD decoder
        return new FacturXDecoder(xmlString);
    }
  }
  
  /**
   * Detects the XML invoice format using string pattern matching
   */
  private static detectFormat(xmlString: string): string {
    // XInvoice/UBL format
    if (xmlString.includes('oasis:names:specification:ubl') || 
        xmlString.includes('Invoice xmlns') ||
        xmlString.includes('xrechnung')) {
      return 'XInvoice/UBL';
    }
    
    // ZUGFeRD/Factur-X (CII format)
    if (xmlString.includes('CrossIndustryInvoice') || 
        xmlString.includes('un/cefact') ||
        xmlString.includes('rsm:')) {
      return 'FacturX/ZUGFeRD';
    }
    
    // Default to FacturX/ZUGFeRD
    return 'FacturX/ZUGFeRD';
  }
}