import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrePlantingRewardStatus } from '../../domain/value-objects/pre-planting-reward-status.enum';
import { PrismaService } from '../../../infrastructure/persistence/prisma/prisma.service';

export interface PrePlantingRewardEntryData {
  sourceOrderNo: string;
  sourceAccountSequence: string;
  recipientAccountSequence: string;
  rightType: string;
  usdtAmount: number;
  rewardStatus: PrePlantingRewardStatus;
  memo?: string;
}

@Injectable()
export class PrePlantingRewardEntryRepository {
  private readonly logger = new Logger(PrePlantingRewardEntryRepository.name);

  constructor(private readonly prisma: PrismaService) {}

  async saveMany(
    tx: Prisma.TransactionClient,
    entries: PrePlantingRewardEntryData[],
  ): Promise<void> {
    if (entries.length === 0) return;

    await tx.prePlantingRewardEntry.createMany({
      data: entries.map((entry) => ({
        sourceOrderNo: entry.sourceOrderNo,
        sourceAccountSequence: entry.sourceAccountSequence,
        recipientAccountSequence: entry.recipientAccountSequence,
        rightType: entry.rightType,
        usdtAmount: new Prisma.Decimal(entry.usdtAmount),
        rewardStatus: entry.rewardStatus,
        memo: entry.memo || null,
      })),
    });

    this.logger.debug(
      `[PRE-PLANTING] Saved ${entries.length} reward entries for order ${entries[0].sourceOrderNo}`,
    );
  }

  async findByOrderNo(
    tx: Prisma.TransactionClient,
    orderNo: string,
  ): Promise<PrePlantingRewardEntryData[]> {
    const records = await tx.prePlantingRewardEntry.findMany({
      where: { sourceOrderNo: orderNo },
    });
    return records.map((r) => ({
      sourceOrderNo: r.sourceOrderNo,
      sourceAccountSequence: r.sourceAccountSequence,
      recipientAccountSequence: r.recipientAccountSequence,
      rightType: r.rightType,
      usdtAmount: Number(r.usdtAmount),
      rewardStatus: r.rewardStatus as PrePlantingRewardStatus,
      memo: r.memo || undefined,
    }));
  }

  async findByAccountSequence(
    tx: Prisma.TransactionClient,
    accountSequence: string,
  ): Promise<PrePlantingRewardEntryData[]> {
    const records = await tx.prePlantingRewardEntry.findMany({
      where: { sourceAccountSequence: accountSequence },
      orderBy: { createdAt: 'desc' },
    });
    return records.map((r) => ({
      sourceOrderNo: r.sourceOrderNo,
      sourceAccountSequence: r.sourceAccountSequence,
      recipientAccountSequence: r.recipientAccountSequence,
      rightType: r.rightType,
      usdtAmount: Number(r.usdtAmount),
      rewardStatus: r.rewardStatus as PrePlantingRewardStatus,
      memo: r.memo || undefined,
    }));
  }

  /**
   * 按收款方账户查询（用于用户查看"我收到的预种奖励"）
   */
  async findByRecipientAccountSequence(
    accountSequence: string,
  ): Promise<(PrePlantingRewardEntryData & { createdAt: Date })[]> {
    const records = await this.prisma.prePlantingRewardEntry.findMany({
      where: { recipientAccountSequence: accountSequence },
      orderBy: { createdAt: 'desc' },
    });
    return records.map((r) => ({
      sourceOrderNo: r.sourceOrderNo,
      sourceAccountSequence: r.sourceAccountSequence,
      recipientAccountSequence: r.recipientAccountSequence,
      rightType: r.rightType,
      usdtAmount: Number(r.usdtAmount),
      rewardStatus: r.rewardStatus as PrePlantingRewardStatus,
      memo: r.memo || undefined,
      createdAt: r.createdAt,
    }));
  }
}
