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

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

  /**
   * 获取系统账户列表
   */
  async getSystemAccounts() {
    // 先从本地 SystemAccount 表获取
    const localAccounts = await this.prisma.systemAccount.findMany({
      orderBy: { accountType: 'asc' },
    });

    // 再从 CDC 同步的 SyncedSystemContribution 获取算力数据
    const syncedContributions =
      await this.prisma.syncedSystemContribution.findMany();

    // 合并数据
    const accountsMap = new Map<string, any>();

    // 添加本地账户
    for (const account of localAccounts) {
      accountsMap.set(account.accountType, {
        accountType: account.accountType,
        name: account.name,
        description: account.description,
        totalContribution: account.totalContribution.toString(),
        createdAt: account.createdAt,
        source: 'local',
      });
    }

    // 更新或添加同步的算力数据
    for (const contrib of syncedContributions) {
      const existing = accountsMap.get(contrib.accountType);
      if (existing) {
        existing.contributionBalance = contrib.contributionBalance.toString();
        existing.contributionNeverExpires = contrib.contributionNeverExpires;
        existing.syncedAt = contrib.syncedAt;
        existing.source = 'synced';
      } else {
        accountsMap.set(contrib.accountType, {
          accountType: contrib.accountType,
          name: contrib.name,
          contributionBalance: contrib.contributionBalance.toString(),
          contributionNeverExpires: contrib.contributionNeverExpires,
          syncedAt: contrib.syncedAt,
          source: 'synced',
        });
      }
    }

    return {
      accounts: Array.from(accountsMap.values()),
      total: accountsMap.size,
    };
  }

  /**
   * 获取系统账户汇总
   */
  async getSystemAccountsSummary() {
    const [localAccounts, syncedContributions, miningConfig, circulationPool] =
      await Promise.all([
        this.prisma.systemAccount.findMany(),
        this.prisma.syncedSystemContribution.findMany(),
        this.prisma.syncedMiningConfig.findFirst(),
        this.prisma.syncedCirculationPool.findFirst(),
      ]);

    // 计算总算力
    let totalSystemContribution = 0n;
    for (const account of localAccounts) {
      totalSystemContribution += BigInt(
        account.totalContribution.toString().replace('.', ''),
      );
    }

    let totalSyncedContribution = 0n;
    for (const contrib of syncedContributions) {
      totalSyncedContribution += BigInt(
        contrib.contributionBalance.toString().replace('.', ''),
      );
    }

    return {
      systemAccounts: {
        count: localAccounts.length,
        totalContribution: (
          Number(totalSystemContribution) / 100000000
        ).toFixed(8),
      },
      syncedContributions: {
        count: syncedContributions.length,
        totalBalance: (Number(totalSyncedContribution) / 100000000).toFixed(8),
      },
      miningConfig: miningConfig
        ? {
            totalShares: miningConfig.totalShares.toString(),
            distributionPool: miningConfig.distributionPool.toString(),
            remainingDistribution: miningConfig.remainingDistribution.toString(),
            currentEra: miningConfig.currentEra,
            isActive: miningConfig.isActive,
            activatedAt: miningConfig.activatedAt,
          }
        : null,
      circulationPool: circulationPool
        ? {
            totalShares: circulationPool.totalShares.toString(),
            totalCash: circulationPool.totalCash.toString(),
          }
        : null,
    };
  }
}
