import { Injectable } from '@nestjs/common';
import { Decimal } from '@prisma/client/runtime/library';
import { PrismaService } from '../../shared/prisma/prisma.service';

export type MatchBetStatsSummary = {
  betCount: number;
  totalStake: string;
  pendingCount: number;
};

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

  /** 批量汇总多场关联注单（按 bet 去重计注单数） */
  async betStatsForMatches(
    matchIds: bigint[],
  ): Promise<Map<string, MatchBetStatsSummary>> {
    const result = new Map<string, MatchBetStatsSummary>();
    if (!matchIds.length) return result;

    const legs = await this.prisma.betSelection.findMany({
      where: { matchId: { in: matchIds } },
      select: {
        matchId: true,
        betId: true,
        bet: { select: { stake: true, status: true } },
      },
    });

    const byMatch = new Map<
      string,
      Map<string, { stake: Decimal; status: string }>
    >();
    for (const leg of legs) {
      if (leg.matchId == null) continue;
      const mid = leg.matchId.toString();
      if (!byMatch.has(mid)) byMatch.set(mid, new Map());
      const bets = byMatch.get(mid)!;
      if (!bets.has(leg.betId.toString())) {
        bets.set(leg.betId.toString(), {
          stake: leg.bet.stake,
          status: leg.bet.status,
        });
      }
    }

    for (const id of matchIds) {
      const mid = id.toString();
      const bets = byMatch.get(mid);
      if (!bets) {
        result.set(mid, {
          betCount: 0,
          totalStake: '0',
          pendingCount: 0,
        });
        continue;
      }
      let totalStake = new Decimal(0);
      let pendingCount = 0;
      for (const b of bets.values()) {
        totalStake = totalStake.add(b.stake);
        if (b.status === 'PENDING') pendingCount += 1;
      }
      result.set(mid, {
        betCount: bets.size,
        totalStake: totalStake.toString(),
        pendingCount,
      });
    }
    return result;
  }
}
