/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
/**
 * @module lib/reporter/models/Finding/Finding
 */
'use strict';
const {
  AGENT_INFO: { TRACE_VERSION }
} = require('../../../constants');
const Event = require('./event');

/**
 * First pass at Finding; this is more or less the representation of an
 * finding object expected by Teamserver.
 */
class Finding {
  /**
   * @param {number} hash
   * @param {string} ruleId
   * @param {Request|IncomingMessage} [request]
   * @param {SinkEvent} [sinkEvent]
   * @param {Object} [properties]
   */
  constructor(hash, ruleId, request, sinkEvent, properties, tags, sessionId) {
    this.hash = hash;
    this.ruleId = ruleId;
    this.properties = properties;
    this.routes = [];
    this.tags = tags;
    this.sessionId = sessionId;
    // convert sink to an array of Event by walking the graph
    this.events = [];
    if (sinkEvent) {
      const events = sinkEvent.getAllParents().add(sinkEvent);
      events.forEach((e) => {
        this.events.push(new Event(e));
      });
    }

    // request is undefined for static rules(hardcoded-password, that's ok)
    this.request = request;
    this.version = TRACE_VERSION;
  }

  toSerializable() {
    const obj = {
      version: this.version,
      hash: this.hash,
      ruleId: this.ruleId,
      properties: this.properties,
      events: this.events,
      request: this.request ? this.request.toSerializable() : null,
      routes: this.routes,
      tags: this.tags
    };

    if (this.sessionId != null && this.sessionId !== '') {
      obj.session_id = String(this.sessionId);
    }

    return obj;
  }
}

module.exports = Finding;
