import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/sequelize"; import { Wallet } from "./entities/wallet.entity"; import { HttpException, HttpStatus } from "@nestjs/common"; import { AddBalanceResponse } from "./add-balance-response.interface"; @Injectable() export class WalletService { constructor(@InjectModel(Wallet) private walletModel: typeof Wallet) {} async getBalance(userId: number){ const wallet = await this.walletModel.findOne({ where: { userId } }); if (!wallet) { throw new HttpException("Wallet not found", HttpStatus.NOT_FOUND); } return { walletId:wallet.id, userId:wallet.userId ,balance: wallet.balance }; } async addBalance(userId: number, amount: number): Promise { try { const wallet = await this.walletModel.findOne({ where: { userId } }); if (wallet) { wallet.balance += amount; await wallet.save(); return { message: "Balance updated successfully.", balance: wallet.balance }; } else { const newWallet = await this.walletModel.create({ userId, balance: amount }); return { message: "Wallet created and balance added successfully.", balance: newWallet.balance }; } } catch (error) { throw new HttpException("An error occurred while adding balance to the wallet.", HttpStatus.INTERNAL_SERVER_ERROR); } } async processPayment(userId: number, amount: number): Promise { const wallet = await this.walletModel.findOne({ where: { userId } }); if (!wallet) { throw new Error("Wallet not found"); } if (wallet.balance < amount) { throw new Error("Insufficient funds"); } wallet.balance -= amount; await wallet.save(); return "Payment processed successfully"; } }