"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getAlertFromRaw = getAlertFromRaw;
exports.getPartialRuleFromRaw = getPartialRuleFromRaw;
var _lodash = require("lodash");
var _lib = require("../../lib");
var _is_rule_snoozed = require("../../lib/is_rule_snoozed");
var _common = require("../common");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

function getAlertFromRaw(context, id, ruleTypeId, rawRule, references, includeLegacyId = false, excludeFromPublicApi = false, includeSnoozeData = false, omitGeneratedValues = true) {
  const ruleType = context.ruleTypeRegistry.get(ruleTypeId);
  // In order to support the partial update API of Saved Objects we have to support
  // partial updates of an Alert, but when we receive an actual RawRule, it is safe
  // to cast the result to an Alert
  const res = getPartialRuleFromRaw(context, id, ruleType, rawRule, references, includeLegacyId, excludeFromPublicApi, includeSnoozeData, omitGeneratedValues);
  // include to result because it is for internal rules client usage
  if (includeLegacyId) {
    return res;
  }
  // exclude from result because it is an internal variable
  return (0, _lodash.omit)(res, ['legacyId']);
}
function getPartialRuleFromRaw(context, id, ruleType, {
  createdAt,
  updatedAt,
  meta,
  notifyWhen,
  legacyId,
  scheduledTaskId,
  params,
  executionStatus,
  monitoring,
  nextRun,
  schedule,
  actions,
  snoozeSchedule,
  lastRun,
  ...partialRawRule
}, references, includeLegacyId = false, excludeFromPublicApi = false, includeSnoozeData = false, omitGeneratedValues = true) {
  var _partialRawRule$muteA, _getActiveScheduledSn, _partialRawRule$muteA2;
  const snoozeScheduleDates = snoozeSchedule === null || snoozeSchedule === void 0 ? void 0 : snoozeSchedule.map(s => ({
    ...s,
    rRule: {
      ...s.rRule,
      dtstart: new Date(s.rRule.dtstart).toISOString(),
      ...(s.rRule.until ? {
        until: new Date(s.rRule.until).toISOString()
      } : {})
    }
  }));
  const includeSnoozeSchedule = snoozeSchedule !== undefined && !(0, _lodash.isEmpty)(snoozeSchedule) && !excludeFromPublicApi;
  const isSnoozedUntil = includeSnoozeSchedule ? (0, _lib.getRuleSnoozeEndTime)({
    muteAll: (_partialRawRule$muteA = partialRawRule.muteAll) !== null && _partialRawRule$muteA !== void 0 ? _partialRawRule$muteA : false,
    snoozeSchedule
  }) : null;
  const includeMonitoring = monitoring && !excludeFromPublicApi;
  const rule = {
    id,
    notifyWhen,
    ...(0, _lodash.omit)(partialRawRule, excludeFromPublicApi ? [...context.fieldsToExcludeFromPublicApi] : ''),
    // we currently only support the Interval Schedule type
    // Once we support additional types, this type signature will likely change
    schedule: schedule,
    actions: actions ? (0, _common.injectReferencesIntoActions)(id, actions, references || []) : [],
    params: (0, _common.injectReferencesIntoParams)(id, ruleType, params, references || []),
    ...(excludeFromPublicApi ? {} : {
      snoozeSchedule: snoozeScheduleDates !== null && snoozeScheduleDates !== void 0 ? snoozeScheduleDates : []
    }),
    ...(includeSnoozeData && !excludeFromPublicApi ? {
      activeSnoozes: (_getActiveScheduledSn = (0, _is_rule_snoozed.getActiveScheduledSnoozes)({
        snoozeSchedule,
        muteAll: (_partialRawRule$muteA2 = partialRawRule.muteAll) !== null && _partialRawRule$muteA2 !== void 0 ? _partialRawRule$muteA2 : false
      })) === null || _getActiveScheduledSn === void 0 ? void 0 : _getActiveScheduledSn.map(s => s.id),
      isSnoozedUntil
    } : {}),
    ...(updatedAt ? {
      updatedAt: new Date(updatedAt)
    } : {}),
    ...(createdAt ? {
      createdAt: new Date(createdAt)
    } : {}),
    ...(scheduledTaskId ? {
      scheduledTaskId
    } : {}),
    ...(executionStatus ? {
      executionStatus: (0, _lib.ruleExecutionStatusFromRaw)(context.logger, id, executionStatus)
    } : {}),
    ...(includeMonitoring ? {
      monitoring: (0, _lib.convertMonitoringFromRawAndVerify)(context.logger, id, monitoring)
    } : {}),
    ...(nextRun ? {
      nextRun: new Date(nextRun)
    } : {}),
    ...(lastRun ? {
      lastRun: {
        ...lastRun,
        ...(lastRun.outcomeMsg && !Array.isArray(lastRun.outcomeMsg) ? {
          outcomeMsg: lastRun.outcomeMsg ? [lastRun.outcomeMsg] : null
        } : {
          outcomeMsg: lastRun.outcomeMsg
        })
      }
    } : {})
  };
  if (omitGeneratedValues) {
    if (rule.actions) {
      rule.actions = rule.actions.map(ruleAction => (0, _lodash.omit)(ruleAction, 'alertsFilter.query.dsl'));
    }
  }

  // Need the `rule` object to build a URL
  if (!excludeFromPublicApi) {
    const viewInAppRelativeUrl = ruleType.getViewInAppRelativeUrl && ruleType.getViewInAppRelativeUrl({
      rule
    });
    if (viewInAppRelativeUrl) {
      rule.viewInAppRelativeUrl = viewInAppRelativeUrl;
    }
  }
  if (includeLegacyId) {
    const result = {
      ...rule,
      legacyId
    };
    return result;
  }
  return rule;
}