/**
 * Authorization Service HTTP 客户端
 * [2026-01-04] 更新：新增系统账户报表统计相关方法
 * 回滚方式：删除 getFixedAccountsList, getRegionAccountsList, getAllAccountsSummary 方法
 */
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';

export interface CompanyStats {
  provinceCompanyCount: number;
  cityCompanyCount: number;
}

export interface CompanyStatsChange {
  provinceCompanyCount: number;
  provinceCompanyChange: number;
  cityCompanyCount: number;
  cityCompanyChange: number;
}

// =============== 系统账户报表相关接口 ===============
// [2026-01-04] 新增：用于系统账户报表统计

export interface SystemAccountDTO {
  id: string;
  accountType: string;
  regionCode: string | null;
  regionName: string | null;
  walletAddress: string | null;
  usdtBalance: string;
  hashpower: string;
  totalReceived: string;
  totalTransferred: string;
  status: string;
  createdAt: string;
  updatedAt: string;
}

export interface RegionAccountsSummary {
  accounts: SystemAccountDTO[];
  summary: {
    totalBalance: string;
    totalReceived: string;
    count: number;
  };
}

export interface AllAccountsSummary {
  fixedAccounts: SystemAccountDTO[];
  provinceSummary: {
    totalBalance: string;
    totalReceived: string;
    count: number;
  };
  citySummary: {
    totalBalance: string;
    totalReceived: string;
    count: number;
  };
}

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

  constructor(private readonly configService: ConfigService) {
    this.baseUrl = this.configService.get<string>(
      'AUTHORIZATION_SERVICE_URL',
      'http://localhost:3004',
    );
  }

  /**
   * 获取公司统计数据
   */
  async getCompanyStats(): Promise<CompanyStats> {
    this.logger.debug(`Fetching company stats from ${this.baseUrl}`);

    try {
      // TODO: 实现真实API调用
      // const response = await axios.get(`${this.baseUrl}/internal/stats/companies`);
      // return response.data;

      // Mock data for development
      return {
        provinceCompanyCount: 28,
        cityCompanyCount: 156,
      };
    } catch (error) {
      this.logger.error('Failed to fetch company stats', error);
      return {
        provinceCompanyCount: 0,
        cityCompanyCount: 0,
      };
    }
  }

  /**
   * 获取公司统计数据（含环比变化）
   */
  async getCompanyStatsWithChange(): Promise<CompanyStatsChange> {
    this.logger.debug(`Fetching company stats with change from ${this.baseUrl}`);

    try {
      // TODO: 实现真实API调用
      // const response = await axios.get(`${this.baseUrl}/internal/stats/companies/change`);
      // return response.data;

      // Mock data for development
      return {
        provinceCompanyCount: 28,
        provinceCompanyChange: 2.1,
        cityCompanyCount: 156,
        cityCompanyChange: 4.8,
      };
    } catch (error) {
      this.logger.error('Failed to fetch company stats with change', error);
      return {
        provinceCompanyCount: 0,
        provinceCompanyChange: 0,
        cityCompanyCount: 0,
        cityCompanyChange: 0,
      };
    }
  }

  // =============== 系统账户报表统计方法 ===============
  // [2026-01-04] 新增：用于系统账户报表统计
  // 回滚方式：删除以下方法即可

  /**
   * 获取固定系统账户列表
   */
  async getFixedAccountsList(): Promise<SystemAccountDTO[]> {
    this.logger.debug(`[getFixedAccountsList] 请求: ${this.baseUrl}/internal/statistics/fixed-accounts`);

    try {
      const response = await axios.get<SystemAccountDTO[]>(
        `${this.baseUrl}/internal/statistics/fixed-accounts`,
      );
      return response.data;
    } catch (error) {
      this.logger.error(`[getFixedAccountsList] 失败: ${error.message}`);
      return [];
    }
  }

  /**
   * 获取区域系统账户列表和汇总
   */
  async getRegionAccountsList(type: 'province' | 'city'): Promise<RegionAccountsSummary> {
    this.logger.debug(`[getRegionAccountsList] 请求: ${this.baseUrl}/internal/statistics/region-accounts?type=${type}`);

    try {
      const response = await axios.get<RegionAccountsSummary>(
        `${this.baseUrl}/internal/statistics/region-accounts?type=${type}`,
      );
      return response.data;
    } catch (error) {
      this.logger.error(`[getRegionAccountsList] 失败: ${error.message}`);
      return {
        accounts: [],
        summary: {
          totalBalance: '0',
          totalReceived: '0',
          count: 0,
        },
      };
    }
  }

  /**
   * 获取所有系统账户汇总
   */
  async getAllAccountsSummary(): Promise<AllAccountsSummary> {
    this.logger.debug(`[getAllAccountsSummary] 请求: ${this.baseUrl}/internal/statistics/all-accounts-summary`);

    try {
      const response = await axios.get<AllAccountsSummary>(
        `${this.baseUrl}/internal/statistics/all-accounts-summary`,
      );
      return response.data;
    } catch (error) {
      this.logger.error(`[getAllAccountsSummary] 失败: ${error.message}`);
      return {
        fixedAccounts: [],
        provinceSummary: {
          totalBalance: '0',
          totalReceived: '0',
          count: 0,
        },
        citySummary: {
          totalBalance: '0',
          totalReceived: '0',
          count: 0,
        },
      };
    }
  }
}
