const UB = require('@unitybase/ub')
// const WebSockets = require('@unitybase/ub/modules/web-sockets')
const Session = UB.Session
/* global uba_audit */
// eslint-disable-next-line camelcase
const me = uba_audit
const ubaCommon = require('@unitybase/base').uba_common

const BY_BORDERID_WHERE_LIST_PREDICATE = '__rlsByBorderID'

uba_audit.entity.addMethod('secureBrowserEvent')

// let __supervisorUserID = 0

// function getSupervisorID () {
//   if (__supervisorUserID === 0) {
//     const supervisorUserName = ubs_settings.loadKey('UBA.securityDashboard.supervisorUser')
//     if (supervisorUserName) {
//       __supervisorUserID = UB.Repository('uba_user').attrs('ID').where('name', '=', supervisorUserName).selectScalar()
//     }
//   }
//   return __supervisorUserID
// }

/**
 * @param {ubMethodParams} ctx
 */
uba_audit.on('insert:after', function notifyAboutSecurity (ctx) {
  // duplicate message into journald/syslog for SIEM
  console.warn('AUDIT=' + JSON.stringify(ctx.mParams.execParams,
    ['entity', 'actionType', 'actionUser', 'remoteIP', 'targetUser', 'targetRole', 'targetGroup', 'userAgent', 'entityinfo_id', 'fromValue']))

  // const notifier = WebSockets.getWSNotifier()
  // if (notifier) {
  //   // Send to specific user
  //   const userSessions = notifier.getUserSessions(getSupervisorID())
  //   userSessions.forEach(function (sessionID) {
  //     notifier.sendCommand('uba_audit_notifier', sessionID, JSON.stringify(ctx.mParams.execParams))
  //   })
  // }
})

const UBA_AUDIT = UB.DataStore('uba_audit')
/**
 * Save an audit events from the secure browser (UnityBase defense edition)
 * @param {ubMethodParams} ctx
 * @param {string} ctx.mParams.reason
 * @param {string} ctx.mParams.action
 * @memberOf uba_audit_ns.prototype
 * @memberOfModule @unitybase/uba
 * @published
 */
function secureBrowserEvent (ctx) {
  const params = ctx.mParams
  const action = params.action || 'DOWNLOAD'
  const reason = params.reason || 'Invalid client call'

  UBA_AUDIT.run('insert', {
    execParams: {
      entity: 'secureBrowser',
      entityinfo_id: 0,
      actionType: action,
      actionUser: Session.uData.login || Session.userID,
      actionTime: new Date(),
      remoteIP: Session.callerIP,
      fromValue: reason
    }
  })
}
me.secureBrowserEvent = secureBrowserEvent

/**
 * returns `ubConfig.security.auditBorderIDuDataProp` value from uData
 * @returns {number|undefined}
 */
function getAuditBorderIdIfApplicable () {
  const auditBorderIDuDataProp = UB.App.serverConfig.security.auditBorderIDuDataProp
  if (!auditBorderIDuDataProp) {
    return
  }
  return Session.uData[auditBorderIDuDataProp] || undefined
}
uba_audit.getAuditBorderIdIfApplicable = getAuditBorderIdIfApplicable
/**
 * in case `ubConfig.security.auditBorderIDuDataProp` is defined add filter by borderID = Session.uData[security.auditBorderIDuDataProp]
 *
 * For other users adds condition what
 *  - either current user is a record owner
 *  - OR user or one of user role in `{$entity}_adm` sub-table
 *
 * @param {ubMethodParams} ctx
 */
uba_audit.borderRLS = function borderRLS (ctx) {
  if (ubaCommon.isSuperUser()) {
    return
  }
  const borderID = getAuditBorderIdIfApplicable()
  if (!borderID) {
    return
  }
  const mParams = ctx.mParams
  let whereList = mParams.whereList
  if (!whereList) {
    mParams.whereList = {}
    // whereList = mParams.whereList = {} assign a {} to whereList instead of TubList instance
    whereList = mParams.whereList
  }
  whereList[BY_BORDERID_WHERE_LIST_PREDICATE] = {
    expression: '[borderID]',
    condition: 'equal',
    value: borderID
  }
}