import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';

@Injectable()
export class PendingContributionsService {
  private readonly logger = new Logger(PendingContributionsService.name);

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {}

  private getMiningServiceUrl(): string {
    return this.configService.get<string>(
      'MINING_SERVICE_URL',
      'http://localhost:3021',
    );
  }

  /**
   * 获取待解锁算力列表
   */
  async getPendingContributions(
    page: number = 1,
    pageSize: number = 20,
    contributionType?: string,
  ) {
    const miningServiceUrl = this.getMiningServiceUrl();

    try {
      const params: any = { page, pageSize };
      if (contributionType) {
        params.contributionType = contributionType;
      }

      const response = await firstValueFrom(
        this.httpService.get(`${miningServiceUrl}/api/v2/mining/admin/pending-contributions`, {
          params,
        }),
      );

      return response.data;
    } catch (error) {
      this.logger.warn(
        `Failed to fetch pending contributions: ${error.message}`,
      );
      return { contributions: [], total: 0, page, pageSize };
    }
  }

  /**
   * 获取待解锁算力汇总统计
   */
  async getPendingContributionsSummary() {
    const miningServiceUrl = this.getMiningServiceUrl();

    try {
      const response = await firstValueFrom(
        this.httpService.get(
          `${miningServiceUrl}/api/v2/mining/admin/pending-contributions/summary`,
        ),
      );

      return response.data;
    } catch (error) {
      this.logger.warn(
        `Failed to fetch pending contributions summary: ${error.message}`,
      );
      return {
        byType: [],
        total: { totalAmount: '0', count: 0 },
        totalMinedToHeadquarters: '0',
      };
    }
  }

  /**
   * 获取某条待解锁算力的挖矿记录
   */
  async getPendingContributionMiningRecords(
    id: string,
    page: number = 1,
    pageSize: number = 20,
  ) {
    const miningServiceUrl = this.getMiningServiceUrl();

    try {
      const response = await firstValueFrom(
        this.httpService.get(
          `${miningServiceUrl}/api/v2/mining/admin/pending-contributions/${id}/records`,
          {
            params: { page, pageSize },
          },
        ),
      );

      return response.data;
    } catch (error) {
      this.logger.warn(
        `Failed to fetch pending contribution mining records: ${error.message}`,
      );
      return {
        pendingContribution: null,
        records: [],
        total: 0,
        page,
        pageSize,
      };
    }
  }

  /**
   * 获取所有待解锁算力的挖矿记录
   */
  async getAllPendingMiningRecords(page: number = 1, pageSize: number = 20) {
    const miningServiceUrl = this.getMiningServiceUrl();

    try {
      const response = await firstValueFrom(
        this.httpService.get(
          `${miningServiceUrl}/api/v2/mining/admin/pending-contributions/mining-records`,
          {
            params: { page, pageSize },
          },
        ),
      );

      return response.data;
    } catch (error) {
      this.logger.warn(
        `Failed to fetch all pending mining records: ${error.message}`,
      );
      return { records: [], total: 0, page, pageSize };
    }
  }
}
