// AS4 Message Canonicalizer Service
// Canonicalizes messages for deterministic signing

export class MessageCanonicalizerService {
  /**
   * Canonicalize JSON message for signing
   * Uses JSON Canonicalization Scheme (JCS)
   */
  canonicalize(message: any): string {
    // Sort keys recursively
    const sorted = this.sortKeys(message);
    // Convert to compact JSON (no whitespace)
    return JSON.stringify(sorted);
  }

  /**
   * Sort object keys recursively
   */
  private sortKeys(obj: any): any {
    if (Array.isArray(obj)) {
      return obj.map((item) => this.sortKeys(item));
    }

    if (obj !== null && typeof obj === 'object') {
      const sorted: any = {};
      const keys = Object.keys(obj).sort();
      for (const key of keys) {
        sorted[key] = this.sortKeys(obj[key]);
      }
      return sorted;
    }

    return obj;
  }

  /**
   * Normalize message for comparison
   */
  normalize(message: any): any {
    const normalized = { ...message };
    
    // Normalize dates to ISO strings
    if (normalized.CreatedAt && typeof normalized.CreatedAt === 'string') {
      normalized.CreatedAt = new Date(normalized.CreatedAt).toISOString();
    }

    // Normalize amounts (remove leading zeros, ensure decimal format)
    if (normalized.Instr?.Amount) {
      const amount = parseFloat(normalized.Instr.Amount).toFixed(2);
      normalized.Instr.Amount = amount;
    }

    return normalized;
  }
}

export const messageCanonicalizerService = new MessageCanonicalizerService();
