import { Injectable } from '@nestjs/common';
import { SyncedDataRepository } from '../../infrastructure/persistence/repositories/synced-data.repository';
import { ContributionAccountRepository } from '../../infrastructure/persistence/repositories/contribution-account.repository';

export interface PlantingRecordDto {
  orderId: string;
  orderNo: string;
  originalAdoptionId: string;
  treeCount: number;
  contributionPerTree: string;
  totalContribution: string;
  status: string;
  adoptionDate: string | null;
  createdAt: string;
}

export interface PlantingSummaryDto {
  totalOrders: number;
  totalTreeCount: number;
  totalAmount: string;
  effectiveTreeCount: number;
  /** 用户实际的有效贡献值（个人算力） */
  effectiveContribution: string;
  firstPlantingAt: string | null;
  lastPlantingAt: string | null;
}

export interface PlantingLedgerDto {
  summary: PlantingSummaryDto;
  items: PlantingRecordDto[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

@Injectable()
export class GetPlantingLedgerQuery {
  constructor(
    private readonly syncedDataRepository: SyncedDataRepository,
    private readonly contributionAccountRepository: ContributionAccountRepository,
  ) {}

  async execute(
    accountSequence: string,
    page: number = 1,
    pageSize: number = 20,
  ): Promise<PlantingLedgerDto> {
    const [summary, ledger, contributionAccount] = await Promise.all([
      this.syncedDataRepository.getPlantingSummary(accountSequence),
      this.syncedDataRepository.getPlantingLedger(accountSequence, page, pageSize),
      this.contributionAccountRepository.findByAccountSequence(accountSequence),
    ]);

    // 获取用户实际的有效贡献值（个人算力）
    const effectiveContribution = contributionAccount?.personalContribution.toString() || '0';

    return {
      summary: {
        totalOrders: summary.totalOrders,
        totalTreeCount: summary.totalTreeCount,
        totalAmount: summary.totalAmount,
        effectiveTreeCount: summary.effectiveTreeCount,
        effectiveContribution,
        firstPlantingAt: summary.firstPlantingAt?.toISOString() || null,
        lastPlantingAt: summary.lastPlantingAt?.toISOString() || null,
      },
      items: ledger.items.map((item) => ({
        orderId: item.id.toString(),
        orderNo: `ORD-${item.originalAdoptionId}`,
        originalAdoptionId: item.originalAdoptionId.toString(),
        treeCount: item.treeCount,
        contributionPerTree: item.contributionPerTree.toString(),
        totalContribution: item.contributionPerTree.mul(item.treeCount).toString(),
        status: item.status || 'UNKNOWN',
        adoptionDate: item.adoptionDate?.toISOString() || null,
        createdAt: item.createdAt.toISOString(),
      })),
      total: ledger.total,
      page: ledger.page,
      pageSize: ledger.pageSize,
      totalPages: ledger.totalPages,
    };
  }
}
