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

function stableValue(value) {
  if (Array.isArray(value)) return value.map(stableValue);
  if (value && typeof value === 'object') {
    return Object.keys(value).sort().reduce((out, key) => {
      out[key] = stableValue(value[key]);
      return out;
    }, {});
  }
  return value;
}

function sha256(value) {
  return crypto
    .createHash('sha256')
    .update(typeof value === 'string' ? value : JSON.stringify(stableValue(value || {})))
    .digest('hex');
}

class RewardAuditLog {
  constructor({
    sourceService,
    actionType,
    category,
    actorId,
    idempotencyKey,
    refId,
    rewardId,
    requestHash,
    validation,
    serviceIdentity,
    status,
    error,
    metadata
  } = {}) {
    this.id = uuidv4();
    this.sourceService = sourceService || 'UNKNOWN';
    this.actionType = actionType || 'UNSPECIFIED';
    this.category = category || 'ecosystem';
    this.actorId = actorId || null;
    this.idempotencyKey = idempotencyKey || '';
    this.refId = refId || '';
    this.rewardId = rewardId || null;
    this.requestHash = requestHash || '';
    this.validation = validation || null;
    this.serviceIdentity = serviceIdentity || null;
    this.status = status || 'accepted';
    this.error = error || '';
    this.metadata = metadata || {};
    this.createdAt = new Date().toISOString();
  }

  static hashRequest(body = {}) {
    return sha256(body);
  }
}

module.exports = RewardAuditLog;
