import BalanceRecord, { BalanceRecordType } from 'App/Models/BalanceRecord'
import UserBalance from 'App/Models/UserBalance'
import Decimal from 'decimal.js'

class UserBalanceService {
    public async getBalance(userId: number) {
        let userBalance = await UserBalance.findBy('userId', userId)
        if (!userBalance) {
            userBalance = await UserBalance.create({
                userId,
                balance: new Decimal(0),
                lastBalance: new Decimal(0)
            })
        }
        return userBalance
    }

    public async modifiyBalance(params: {
        userId: number
        amount: Decimal
        type: BalanceRecordType
        description?: string
        seriesId?: number
        episodeId?: number
        episodeNum?: number
    }) {
        const userBalance = await this.getBalance(params.userId)
        userBalance.lastBalance = userBalance.balance
        userBalance.balance = userBalance.balance.plus(params.amount)
        await userBalance.save()

        const balanceRecord = new BalanceRecord()
        balanceRecord.merge(params)
        balanceRecord.balance = userBalance.balance
        balanceRecord.lastBalance = userBalance.lastBalance
        await balanceRecord.save()
    }
}
export default new UserBalanceService()
