// AS4 Receipt Service
// Generates and validates AS4 receipts (NRO/NRR)

import { v4 as uuidv4 } from 'uuid';
import { as4SecurityService } from './as4-security.service';
import { logger } from '@/infrastructure/monitoring/logger';

export interface As4Receipt {
  receiptId: string;
  messageId: string;
  timestamp: Date;
  receiptType: 'NRO' | 'NRR'; // Non-Repudiation of Origin / Receipt
  signature?: {
    algorithm: string;
    signature: string;
    certificateFingerprint: string;
  };
  properties?: Record<string, string>;
}

export class As4ReceiptService {
  /**
   * Generate AS4 receipt (NRR - Non-Repudiation of Receipt)
   */
  async generateReceipt(
    messageId: string,
    memberId: string,
    receiptType: 'NRO' | 'NRR' = 'NRR'
  ): Promise<As4Receipt> {
    const receiptId = `RECEIPT-${uuidv4()}`;
    const timestamp = new Date();

    // Create receipt payload
    const receiptPayload = JSON.stringify({
      receiptId,
      messageId,
      timestamp: timestamp.toISOString(),
      receiptType,
    });

    // Sign receipt
    const signature = await as4SecurityService.signMessage(receiptPayload, memberId);

    const receipt: As4Receipt = {
      receiptId,
      messageId,
      timestamp,
      receiptType,
      signature: {
        algorithm: signature.algorithm,
        signature: signature.signature,
        certificateFingerprint: signature.certificateFingerprint,
      },
    };

    logger.info('AS4 receipt generated', {
      receiptId,
      messageId,
      receiptType,
      memberId,
    });

    return receipt;
  }

  /**
   * Validate AS4 receipt
   */
  async validateReceipt(receipt: As4Receipt, memberId: string): Promise<boolean> {
    if (!receipt.signature) {
      logger.warn('Receipt missing signature', { receiptId: receipt.receiptId });
      return false;
    }

    // Reconstruct receipt payload
    const receiptPayload = JSON.stringify({
      receiptId: receipt.receiptId,
      messageId: receipt.messageId,
      timestamp: receipt.timestamp.toISOString(),
      receiptType: receipt.receiptType,
    });

    // Verify signature
    const isValid = await as4SecurityService.verifyMessageSignature(
      receiptPayload,
      receipt.signature,
      memberId
    );

    if (!isValid) {
      logger.warn('Receipt signature validation failed', {
        receiptId: receipt.receiptId,
        memberId,
      });
    }

    return isValid;
  }

  /**
   * Generate business receipt (in addition to AS4 receipt)
   */
  async generateBusinessReceipt(
    messageId: string,
    businessType: string,
    status: string,
    memberId: string
  ): Promise<As4Receipt> {
    const receiptId = `BUSINESS-RECEIPT-${uuidv4()}`;
    const timestamp = new Date();

    const receiptPayload = JSON.stringify({
      receiptId,
      messageId,
      businessType,
      status,
      timestamp: timestamp.toISOString(),
    });

    const signature = await as4SecurityService.signMessage(receiptPayload, memberId);

    return {
      receiptId,
      messageId,
      timestamp,
      receiptType: 'NRR',
      signature: {
        algorithm: signature.algorithm,
        signature: signature.signature,
        certificateFingerprint: signature.certificateFingerprint,
      },
      properties: {
        businessType,
        status,
      },
    };
  }
}

export const as4ReceiptService = new As4ReceiptService();
