const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');

class ProofLedger {
  constructor({
    sourceService,
    proofType,
    actorId,
    targetId,
    deviceId,
    nodeId,
    externalProofId,
    idempotencyKey,
    userIdHash,
    contentHash,
    chunkHash,
    payloadHash,
    proofHash,
    bundleHash,
    merkleRoot,
    metadata
  } = {}) {
    this.id = uuidv4();
    this.sourceService = sourceService || 'UNKNOWN';
    this.proofType = proofType || 'ACTIVITY';
    this.actorId = actorId || null;
    this.targetId = targetId || null;
    this.deviceId = deviceId || null;
    this.nodeId = nodeId || null;
    this.externalProofId = externalProofId || null;
    this.idempotencyKey = idempotencyKey || null;
    this.userIdHash = userIdHash || null;
    this.contentHash = contentHash || chunkHash || this.createContentHash(metadata);
    this.chunkHash = chunkHash || null;
    this.payloadHash = payloadHash || null;
    this.proofHash = proofHash || null;
    this.bundleHash = bundleHash || null;
    this.merkleRoot = merkleRoot || null;
    this.metadata = metadata || {};
    this.chainTransactionId = null;
    this.txHash = null;
    this.status = 'CREATED';
    this.createdAt = new Date().toISOString();
  }

  createContentHash(metadata) {
    return crypto
      .createHash('sha256')
      .update(JSON.stringify(metadata || {}))
      .digest('hex');
  }

  attachTransaction(transaction) {
    this.chainTransactionId = transaction.id;
    this.txHash = transaction.txHash;
    this.status = 'ANCHORED_MOCK';
  }
}

module.exports = ProofLedger;
