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

export interface TreePricingConfig {
  basePrice: number;
  basePortionPrice: number;
  currentSupplement: number;
  totalPrice: number;
  totalPortionPrice: number;
  autoIncreaseEnabled: boolean;
  autoIncreaseAmount: number;
  autoIncreaseIntervalDays: number;
  nextAutoIncreaseAt: string | null;
}

/**
 * HTTP 客户端：从 admin-service 获取当前树定价配置
 *
 * 涨价原因：总部运营成本压力，加价部分全额归总部 (S0000000001)
 * 遵循 PrePlantingAdminClient 模式
 */
@Injectable()
export class TreePricingAdminClient {
  private readonly logger = new Logger(TreePricingAdminClient.name);
  private readonly baseUrl: string;

  constructor(
    private readonly configService: ConfigService,
    private readonly httpService: HttpService,
  ) {
    this.baseUrl =
      this.configService.get<string>('ADMIN_SERVICE_URL') ||
      'http://localhost:3010';
  }

  async getTreePricingConfig(): Promise<TreePricingConfig> {
    try {
      const response = await firstValueFrom(
        this.httpService.get<TreePricingConfig>(
          `${this.baseUrl}/api/v1/tree-pricing/config`,
        ),
      );
      return response.data;
    } catch (error) {
      this.logger.error('Failed to get tree pricing config, using default (supplement=0)', error);
      // 安全降级：加价为 0，不影响现有业务
      return {
        basePrice: 15831,
        basePortionPrice: 1887,
        currentSupplement: 0,
        totalPrice: 15831,
        totalPortionPrice: 1887,
        autoIncreaseEnabled: false,
        autoIncreaseAmount: 0,
        autoIncreaseIntervalDays: 0,
        nextAutoIncreaseAt: null,
      };
    }
  }
}
