import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Payout, PayoutStatus } from './entities/payout.entity';
import { StripeService } from './stripe.service';
import { PayPalService } from './paypal.service';
@Injectable()
export class PayoutService {
constructor(
@InjectRepository(Payout) private readonly payoutRepo: Repository<Payout>,
private readonly stripeService: StripeService,
private readonly paypalService: PayPalService,
) {}
async createPayout(sellerId: string, amount: number, method: string): Promise<Payout> {
const payout = this.payoutRepo.create({ sellerId, amount, method, status: PayoutStatus.PENDING });
const saved = await this.payoutRepo.save(payout);
if (method === 'stripe') {
await this.stripeService.createTransfer({
amount: Math.round(amount * 100), currency: 'usd',
destination: 'stripe_account_id', description: `Payout for seller ${sellerId}`,
});
} else if (method === 'paypal') {
await this.paypalService.createPayout({
senderBatchId: `payout_${sellerId}_${Date.now()}`,
items: [{ recipientType: 'EMAIL', amount: { value: amount.toString(), currency: 'USD' }, receiver: 'seller@email.com' }],
});
}
saved.status = PayoutStatus.COMPLETED;
return this.payoutRepo.save(saved);
}
async getPayoutHistory(sellerId: string): Promise<Payout[]> {
return this.payoutRepo.find({ where: { sellerId }, order: { createdAt: 'DESC' } });
}
}