import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { SettlementRecord as PrismaSettlementRecord } from '@prisma/client';

export interface SettlementRecordDto {
  id: string;
  userId: string;
  accountSequence: string;
  usdtAmount: number;
  hashpowerAmount: number;
  settleCurrency: string;
  receivedAmount: number;
  swapTxHash: string | null;
  swapRate: number | null;
  status: string;
  createdAt: Date;
  completedAt: Date | null;
  rewardEntryIds: string[];
}

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

  /**
   * 查询用户的结算历史记录
   */
  async findByAccountSequence(
    accountSequence: string,
    pagination?: { page: number; pageSize: number },
  ): Promise<SettlementRecordDto[]> {
    const skip = pagination ? (pagination.page - 1) * pagination.pageSize : undefined;
    const take = pagination?.pageSize;

    const rawList = await this.prisma.settlementRecord.findMany({
      where: { accountSequence },
      orderBy: { createdAt: 'desc' },
      skip,
      take,
    });

    return rawList.map(this.toDto);
  }

  /**
   * 统计用户的结算记录数量
   */
  async countByAccountSequence(accountSequence: string): Promise<number> {
    return this.prisma.settlementRecord.count({
      where: { accountSequence },
    });
  }

  /**
   * 根据ID查询结算记录
   */
  async findById(id: bigint): Promise<SettlementRecordDto | null> {
    const raw = await this.prisma.settlementRecord.findUnique({
      where: { id },
    });
    return raw ? this.toDto(raw) : null;
  }

  private toDto(raw: PrismaSettlementRecord): SettlementRecordDto {
    return {
      id: raw.id.toString(),
      userId: raw.userId.toString(),
      accountSequence: raw.accountSequence,
      usdtAmount: Number(raw.usdtAmount),
      hashpowerAmount: Number(raw.hashpowerAmount),
      settleCurrency: raw.settleCurrency,
      receivedAmount: Number(raw.receivedAmount),
      swapTxHash: raw.swapTxHash,
      swapRate: raw.swapRate ? Number(raw.swapRate) : null,
      status: raw.status,
      createdAt: raw.createdAt,
      completedAt: raw.completedAt,
      rewardEntryIds: raw.rewardEntryIds.map(id => id.toString()),
    };
  }
}
