/**
 * Reward Service HTTP 客户端
 * [2026-01-04] 新增：用于系统账户报表统计
 * [2026-01-06] 更新：添加收益类型汇总统计接口
 * 回滚方式：删除此文件
 */

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

export interface ExpiredRewardsSummary {
  totalAmount: number;
  totalCount: number;
  byMonth: Array<{
    month: string;
    amount: number;
    count: number;
  }>;
  byRightType: Array<{
    rightType: string;
    amount: number;
    count: number;
  }>;
}

// [2026-01-06] 新增：收益类型汇总接口类型
// [2026-01-06] 更新：添加全量统计字段（包含所有状态）
export interface RewardTypeSummary {
  totalAmount: number;
  totalCount: number;
  totalSettleableAmount: number;
  totalSettledAmount: number;
  // [2026-01-06] 新增：全量统计（包含所有状态）
  allStatusTotalAmount: number;
  allStatusTotalCount: number;
  pendingAmount: number;
  pendingCount: number;
  expiredAmount: number;
  expiredCount: number;
  byStatus: Array<{
    status: string;
    amount: number;
    count: number;
  }>;
  byMonth: Array<{
    month: string;
    amount: number;
    count: number;
  }>;
}

export interface FeeAccountSummary {
  totalAmount: number;
  totalCount: number;
  breakdown: Array<{
    rightType: string;
    amount: number;
    count: number;
  }>;
}

export interface AllRewardTypeSummaries {
  feeAccountSummary: FeeAccountSummary;
  provinceTeamSummary: RewardTypeSummary;
  cityTeamSummary: RewardTypeSummary;
  shareReferralSummary: RewardTypeSummary;
  communitySummary: RewardTypeSummary;
}

// [2026-01-06] 新增：收益记录条目
// [2026-02-05] 更新：添加 sourceAccountSequence 字段
export interface RewardEntryDTO {
  id: string;
  accountSequence: string;
  sourceAccountSequence: string | null;  // 来源用户账户序列号
  sourceOrderId: string;
  rightType: string;
  rewardStatus: string;
  usdtAmount: number;
  hashpowerAmount: number;
  createdAt: string;
  claimedAt: string | null;
  expiredAt: string | null;
}

// [2026-01-07] 新增：过期收益明细条目
export interface ExpiredRewardEntryDTO {
  id: string;
  accountSequence: string;
  userId: number;
  sourceOrderId: string;
  rightType: string;
  usdtAmount: number;
  hashpowerAmount: number;
  createdAt: string;
  expiredAt: string | null;
}

// [2026-01-07] 新增：过期收益明细响应
export interface ExpiredRewardsEntriesResponse {
  entries: ExpiredRewardEntryDTO[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// [2026-01-06] 新增：收益记录列表响应
export interface RewardEntriesResponse {
  entries: RewardEntryDTO[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

@Injectable()
export class RewardServiceClient {
  private readonly logger = new Logger(RewardServiceClient.name);
  private readonly baseUrl: string;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.baseUrl = this.configService.get<string>(
      'REWARD_SERVICE_URL',
      'http://rwa-reward-service:3005',
    );
  }

  /**
   * 获取过期收益统计汇总
   */
  async getExpiredRewardsSummary(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<ExpiredRewardsSummary> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.startDate) queryParams.append('startDate', params.startDate);
      if (params?.endDate) queryParams.append('endDate', params.endDate);

      const url = `${this.baseUrl}/api/v1/internal/statistics/expired-rewards-summary?${queryParams.toString()}`;
      this.logger.debug(`[getExpiredRewardsSummary] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<ExpiredRewardsSummary>(url),
      );

      return response.data;
    } catch (error) {
      this.logger.error(`[getExpiredRewardsSummary] 失败: ${error.message}`);
      // 返回默认值，不阻塞报表
      return {
        totalAmount: 0,
        totalCount: 0,
        byMonth: [],
        byRightType: [],
      };
    }
  }

  // [2026-01-06] 新增：获取所有收益类型汇总统计
  /**
   * 获取所有收益类型的汇总统计
   * 包括：手续费汇总、省团队收益汇总、市团队收益汇总、分享引荐收益汇总、社区收益汇总
   */
  async getAllRewardTypeSummaries(): Promise<AllRewardTypeSummaries> {
    try {
      const url = `${this.baseUrl}/api/v1/internal/statistics/reward-type-summaries`;
      this.logger.debug(`[getAllRewardTypeSummaries] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<AllRewardTypeSummaries>(url),
      );

      return response.data;
    } catch (error) {
      this.logger.error(`[getAllRewardTypeSummaries] 失败: ${error.message}`);
      // 返回默认值，不阻塞报表
      const defaultSummary: RewardTypeSummary = {
        totalAmount: 0,
        totalCount: 0,
        totalSettleableAmount: 0,
        totalSettledAmount: 0,
        allStatusTotalAmount: 0,
        allStatusTotalCount: 0,
        pendingAmount: 0,
        pendingCount: 0,
        expiredAmount: 0,
        expiredCount: 0,
        byStatus: [],
        byMonth: [],
      };
      return {
        feeAccountSummary: {
          totalAmount: 0,
          totalCount: 0,
          breakdown: [],
        },
        provinceTeamSummary: defaultSummary,
        cityTeamSummary: defaultSummary,
        shareReferralSummary: defaultSummary,
        communitySummary: defaultSummary,
      };
    }
  }

  // [2026-01-06] 新增：获取收益类型详细记录列表
  /**
   * 获取指定收益类型的详细记录列表
   */
  async getRewardEntriesByType(params: {
    rightType: string;
    page?: number;
    pageSize?: number;
  }): Promise<RewardEntriesResponse> {
    try {
      const queryParams = new URLSearchParams();
      queryParams.append('rightType', params.rightType);
      if (params.page) queryParams.append('page', params.page.toString());
      if (params.pageSize) queryParams.append('pageSize', params.pageSize.toString());

      const url = `${this.baseUrl}/api/v1/internal/statistics/reward-entries-by-type?${queryParams.toString()}`;
      this.logger.debug(`[getRewardEntriesByType] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<RewardEntriesResponse>(url),
      );

      return response.data;
    } catch (error) {
      this.logger.error(`[getRewardEntriesByType] 失败: ${error.message}`);
      return {
        entries: [],
        total: 0,
        page: 1,
        pageSize: params.pageSize ?? 50,
        totalPages: 0,
      };
    }
  }

  /**
   * 获取手续费类型的详细记录列表
   */
  async getFeeEntriesDetailed(params?: {
    page?: number;
    pageSize?: number;
  }): Promise<RewardEntriesResponse> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.page) queryParams.append('page', params.page.toString());
      if (params?.pageSize) queryParams.append('pageSize', params.pageSize.toString());

      const url = `${this.baseUrl}/api/v1/internal/statistics/fee-entries-detailed?${queryParams.toString()}`;
      this.logger.debug(`[getFeeEntriesDetailed] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<RewardEntriesResponse>(url),
      );

      return response.data;
    } catch (error) {
      this.logger.error(`[getFeeEntriesDetailed] 失败: ${error.message}`);
      return {
        entries: [],
        total: 0,
        page: 1,
        pageSize: params?.pageSize ?? 50,
        totalPages: 0,
      };
    }
  }

  // [2026-01-07] 新增：获取过期收益明细列表
  /**
   * 获取过期收益明细列表
   */
  async getExpiredRewardsEntries(params?: {
    page?: number;
    pageSize?: number;
    rightType?: string;
  }): Promise<ExpiredRewardsEntriesResponse> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.page) queryParams.append('page', params.page.toString());
      if (params?.pageSize) queryParams.append('pageSize', params.pageSize.toString());
      if (params?.rightType) queryParams.append('rightType', params.rightType);

      const url = `${this.baseUrl}/api/v1/internal/statistics/expired-rewards-entries?${queryParams.toString()}`;
      this.logger.debug(`[getExpiredRewardsEntries] 请求: ${url}`);

      const response = await firstValueFrom(
        this.httpService.get<ExpiredRewardsEntriesResponse>(url),
      );

      return response.data;
    } catch (error) {
      this.logger.error(`[getExpiredRewardsEntries] 失败: ${error.message}`);
      return {
        entries: [],
        total: 0,
        page: 1,
        pageSize: params?.pageSize ?? 50,
        totalPages: 0,
      };
    }
  }
}
