import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

@Injectable()
export class DonationsService {
  constructor(private prisma: PrismaService) {}

  async getList(limit = 20) {
    const donations = await this.prisma.donation.findMany({
      orderBy: { createdAt: 'desc' },
      take: limit,
      select: {
        id: true,
        name: true,
        message: true,
        channel: true,
        amount: true,
        createdAt: true,
      },
    });
    return {
      donations: donations.map((d) => ({
        ...d,
        amount: d.amount != null ? Number(d.amount) : null,
      })),
    };
  }

  async create(data: {
    name?: string;
    message?: string;
    channel?: 'ALIPAY' | 'WECHAT';
    amount?: number;
  }) {
    const donation = await this.prisma.donation.create({
      data: {
        name: data.name ?? null,
        message: data.message ?? null,
        channel: data.channel ?? 'ALIPAY',
        amount: data.amount != null ? data.amount : null,
      },
    });
    return {
      success: true,
      donation: {
        ...donation,
        amount: donation.amount != null ? Number(donation.amount) : null,
      },
    };
  }
}
