import { BadRequestException, Injectable, InternalServerErrorException, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { UserBalance } from './entities/user-balance.entity'
import { Repository } from 'typeorm'
import { BalanceRecord, BalanceType } from './entities/balance-record.entity'
import { BigNumber } from 'bignumber.js'

@Injectable()
export class UserBalanceService {
    constructor(
        @InjectRepository(UserBalance)
        private readonly userBalanceRepository: Repository<UserBalance>,
        @InjectRepository(BalanceRecord)
        private readonly balanceRecordRepository: Repository<BalanceRecord>
    ) {}

    async getBalance(userId: number): Promise<UserBalance> {
        let userBalance = await this.userBalanceRepository.findOneBy({ userId })
        if (!userBalance) {
            userBalance = new UserBalance({
                userId,
                balance: new BigNumber(0),
                lastBalance: new BigNumber(0)
            })
            await this.userBalanceRepository.save(userBalance)
        }
        return userBalance
    }

    async modifyBalance(userId: number, amount: BigNumber, type: BalanceType, remark?: string, extra?: string) {
        const userBalance = await this.getBalance(userId)
        const balance = userBalance.balance.plus(amount)
        if (balance.comparedTo(new BigNumber(0)) < 0) {
            throw new BadRequestException('余额不足')
        }
        Logger.log(userBalance.balance.plus(amount), '余额')
        await this.balanceRecordRepository.save(
            new BalanceRecord({
                userId,
                amount,
                balance,
                lastBalance: userBalance.balance,
                type,
                remark,
                extra
            })
        )
        userBalance.lastBalance = userBalance.balance
        userBalance.balance = balance
        await this.userBalanceRepository.save(userBalance)
    }

    async getRecords(userId: number) {
        return await this.balanceRecordRepository.find({
            where: {
                userId
            },
            order: {
                createdAt: 'DESC'
            }
        })
    }
}
