/**
 *  @module     Transaction
 *  @overview   Defines the points transactions logic and interfaces
 *  
 *  @author     Animesh Mishra <hello@animesh.ltd>
 *  @copyright  © 2018 Animesh Ltd. All Rights Reserved.
 */

import { ObjectID } from "mongodb"

const milliSecondsInAYear = 31557600000
/**
 *  Operations such as issuance, redemptions, rollback, refund etc. are classified as Points
 *  Transactions and managed by the `Transaction` class.
 *  
 *  Each `transaction` carries a unique `_id`.
 */
export class Transaction {
    /** Unique transaction reference */
    public readonly _id: string

    /** Points used in the transaction */
    public readonly points: number

    /** Type of transaction. Could be either of Issue, Redeem or Refund */
    public readonly type: string

    /** Date and time of transaction */
    public readonly date: Date

    /** Any notes attached to the transaction request */
    public notes: string

    /** 
     *  For points issuance, an expiry date 365 days in the future will be
     *  set. This won't be set for other kinds of transactions.
     */
    public readonly expiryDate?: Date

    /**
     *  Initialises a Points `Transaction` instance.
     *  
     *  @param {InitTransaction} json See `Source/Transaction.ts` for definition
     *                                of `InitTransaction`. 
     */
    public constructor(json: InitTransaction) {
        this._id        = json._id || new ObjectID().toHexString()
        this.points     = json.points
        this.type       = json.type
        this.date       = json.date ? new Date(json.date!) : new Date()
        this.notes      = json.notes
        this.expiryDate = json.expiryDate ? new Date(json.expiryDate!) : new Date(Date.now() + milliSecondsInAYear)
    }
}

export interface InitTransaction {
    _id?: string,
    points: number,
    type: string,
    date?: Date,
    notes: string,
    expiryDate?: Date
}