import mongoose, { Document, Model } from 'mongoose';

import { MODEL_NAMES } from './_models';

export enum ELogType {
  TRANSACTIONS_UPLOAD = 'TRANSACTIONS_UPLOAD',
  COLLATERAL_UPLOAD = 'COLLATERAL_UPLOAD',
  LOAN_TRANSACTION = 'LOAN_TRANSACTION',
  RECEIVABLE_AVAILABILITY = 'RECEIVABLE_AVAILABILITY',
  INVENTORY_AVAILABILITY = 'INVENTORY_AVAILABILITY',
  EQUIPMENT = 'EQUIPMENT',
  RESERVES = 'RESERVES',
  COLLATERAL_ADJUSTMENTS = 'COLLATERAL_ADJUSTMENTS',
  LOGIN = 'LOGIN',
  SIGN_BBC = 'SIGN_BBC',
  REVOKE_BBC = 'REVOKE_BBC',
  PROSPECT = 'PROSPECT',
}

export enum ELogActionType {
  UPLOAD = 'UPLOAD',
  CREATE = 'CREATE',
  EDIT = 'EDIT',
  DELETE = 'DELETE',
}

export interface IUserLog {
  logType: ELogType;
  userId: string;
  timestamp: Date;
  action: ELogActionType;
  recordId: mongoose.Types.ObjectId;
  recordCollection: string;
  details: any;
}

export interface IUserLogDoc extends IUserLog, Document {
}

export interface IUserLogWithLookup extends IUserLog {
  record?: any;
}

type UserLogModel = Model<IUserLog, {}, {}>;

export const UserLogSchema = new mongoose.Schema<IUserLog, UserLogModel>(
  {
    logType: {
      type: String,
      enum: Object.values(ELogType),
      required: true,
    },
    userId: {
      type: String,
      required: true,
    },
    timestamp: {
      type: Date,
      required: true,
    },
    action: {
      type: String,
      enum: Object.values(ELogActionType),
      required: true,
    },
    recordId: {
      type: mongoose.Schema.Types.ObjectId,
    },
    recordCollection: {
      type: String,
    },
    details: {
      type: mongoose.Schema.Types.Mixed,
      required: true,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: false },
  },
);

export const UserLog = mongoose.model<IUserLog, UserLogModel>(MODEL_NAMES.userLogs, UserLogSchema);
