// AS4 Evidence Vault Service
// WORM storage for compliance evidence

import { as4PayloadVaultService } from '../../as4/as4-payload-vault.service';
import { logger } from '@/infrastructure/monitoring/logger';

export interface EvidencePackage {
  packageId: string;
  instructionId: string;
  screeningResults: any;
  amlResults: any;
  timestamp: Date;
}

export class EvidenceVaultService {
  /**
   * Store evidence package
   */
  async storeEvidence(data: {
    instructionId: string;
    screeningResults: any;
    amlResults: any;
    payload: string;
  }): Promise<EvidencePackage> {
    const packageId = `EVIDENCE-${Date.now()}`;

    // Store evidence payload in vault
    await as4PayloadVaultService.storePayload({
      instructionId: data.instructionId,
      messageId: packageId,
      payload: JSON.stringify({
        screeningResults: data.screeningResults,
        amlResults: data.amlResults,
      }),
      payloadType: 'INSTRUCTION',
      memberId: 'DBIS',
    });

    const package_: EvidencePackage = {
      packageId,
      instructionId: data.instructionId,
      screeningResults: data.screeningResults,
      amlResults: data.amlResults,
      timestamp: new Date(),
    };

    logger.info('Evidence package stored', {
      packageId,
      instructionId: data.instructionId,
    });

    return package_;
  }

  /**
   * Retrieve evidence package
   */
  async retrieveEvidence(packageId: string): Promise<EvidencePackage | null> {
    // Retrieve from payload vault
    const payload = await as4PayloadVaultService.retrievePayloadByMessageId(packageId);
    if (payload.length === 0) {
      return null;
    }

    const payloadData = JSON.parse(await as4PayloadVaultService.retrievePayload(payload[0].vaultId) || '{}');

    return {
      packageId,
      instructionId: payload[0].instructionId || '',
      screeningResults: payloadData.screeningResults,
      amlResults: payloadData.amlResults,
      timestamp: payload[0].createdAt,
    };
  }
}

export const evidenceVaultService = new EvidenceVaultService();
