import _ from 'lodash';
import mongoose from 'mongoose';

import { ELogActionType, ELogType, UserLog } from '../models/UserLog.model';

const excludedKeys = ['$set', '$setOnInsert'];

const createLogs = true;

export interface ICreateLogParams {
  logType: ELogType,
  userId: string,
  action: ELogActionType,
  details: Object,
  recordId?: mongoose.Types.ObjectId;
  recordCollection?: string;
  timestamp?: Date;
}

export const createLog = async (params: ICreateLogParams) => {
  if (!createLogs) {
    return;
  }
  if (!params.userId) {
    return;
  }
  const newUserLog = new UserLog({
    timestamp: params.timestamp ? params.timestamp : new Date(),
    logType: params.logType,
    userId: params.userId,
    action: params.action,
    details: params.details,
    recordId: params.recordId,
    recordCollection: params.recordCollection,
  });
  try {
    await newUserLog.save();
  } catch (e) {
    console.error(`incorrect log`, newUserLog, e );
    throw e;
  }
}

export const getLogChanges = (obj1: Object, obj2: Object) => {
  const changedKeys = _.pickBy(obj2, (value, key) => {
    if (excludedKeys.includes(key)) {
      return false;
    }
    const oldValue = obj1[key] ? obj1[key].toString() : obj1[key];
    const newValue = value ? value.toString() : value;
    return oldValue !== newValue;
  });
  return Object.keys(changedKeys).reduce((acc, key) => ({
    ...acc,
    [key]: { oldValue: obj1[key], newValue: obj2[key] },
  }), {});
}
