import { Injectable } from '@nestjs/common';
import { ContributionAccountRepository } from '../../infrastructure/persistence/repositories/contribution-account.repository';
import { ContributionRecordRepository } from '../../infrastructure/persistence/repositories/contribution-record.repository';
import { UnallocatedContributionRepository } from '../../infrastructure/persistence/repositories/unallocated-contribution.repository';
import { SystemAccountRepository } from '../../infrastructure/persistence/repositories/system-account.repository';
import { SyncedDataRepository } from '../../infrastructure/persistence/repositories/synced-data.repository';
import { ContributionSourceType } from '../../domain/aggregates/contribution-account.aggregate';

export interface ContributionStatsDto {
  // 用户统计
  totalUsers: number;
  totalAccounts: number;
  accountsWithContribution: number;

  // 认种统计
  totalAdoptions: number;
  processedAdoptions: number;
  unprocessedAdoptions: number;

  // 算力统计
  totalContribution: string;

  // 算力分布
  contributionByType: {
    personal: string;
    teamLevel: string;
    teamBonus: string;
  };

  // 系统账户
  systemAccounts: {
    accountType: string;
    name: string;
    totalContribution: string;
  }[];

  // 未分配算力
  totalUnallocated: string;
  unallocatedByType: Record<string, string>;
}

@Injectable()
export class GetContributionStatsQuery {
  constructor(
    private readonly accountRepository: ContributionAccountRepository,
    private readonly recordRepository: ContributionRecordRepository,
    private readonly unallocatedRepository: UnallocatedContributionRepository,
    private readonly systemAccountRepository: SystemAccountRepository,
    private readonly syncedDataRepository: SyncedDataRepository,
  ) {}

  async execute(): Promise<ContributionStatsDto> {
    const [
      totalUsers,
      totalAccounts,
      accountsWithContribution,
      totalAdoptions,
      undistributedAdoptions,
      totalContribution,
      contributionByType,
      systemAccounts,
      totalUnallocated,
      unallocatedByType,
    ] = await Promise.all([
      this.syncedDataRepository.countUsers(),
      this.accountRepository.countAccounts(),
      this.accountRepository.countAccountsWithContribution(),
      this.syncedDataRepository.countAdoptions(),
      this.syncedDataRepository.countUndistributedAdoptions(),
      this.accountRepository.getTotalContribution(),
      this.recordRepository.getContributionSummaryBySourceType(),
      this.systemAccountRepository.findAll(),
      this.unallocatedRepository.getTotalUnallocated(),
      this.unallocatedRepository.getTotalUnallocatedByType(),
    ]);

    return {
      totalUsers,
      totalAccounts,
      accountsWithContribution,
      totalAdoptions,
      processedAdoptions: totalAdoptions - undistributedAdoptions,
      unprocessedAdoptions: undistributedAdoptions,
      totalContribution: totalContribution.value.toString(),
      contributionByType: {
        personal: (contributionByType.get(ContributionSourceType.PERSONAL)?.value || 0).toString(),
        teamLevel: (contributionByType.get(ContributionSourceType.TEAM_LEVEL)?.value || 0).toString(),
        teamBonus: (contributionByType.get(ContributionSourceType.TEAM_BONUS)?.value || 0).toString(),
      },
      systemAccounts: systemAccounts.map((a) => ({
        accountType: a.accountType,
        name: a.name,
        totalContribution: a.contributionBalance.value.toString(),
      })),
      totalUnallocated: totalUnallocated.value.toString(),
      unallocatedByType: Object.fromEntries(
        Array.from(unallocatedByType.entries()).map(([k, v]) => [k, v.value.toString()]),
      ),
    };
  }
}
