/**
 * 预种计划数据代理服务
 * [2026-02-27] 新增：通过内部 HTTP 调用 planting-service 获取预种管理数据
 *
 * === 架构 ===
 * admin-web → admin-service (本服务) → planting-service /internal/pre-planting/admin/*
 * 复用现有 ContractService 的 axios 代理模式
 */

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

@Injectable()
export class PrePlantingProxyService {
  private readonly logger = new Logger(PrePlantingProxyService.name);
  private readonly httpClient: AxiosInstance;

  constructor(private readonly configService: ConfigService) {
    const plantingServiceUrl = this.configService.get<string>(
      'PLANTING_SERVICE_URL',
      'http://rwa-planting-service:3003',
    );

    this.httpClient = axios.create({
      baseURL: plantingServiceUrl,
      timeout: 30000,
    });

    this.logger.log(
      `PrePlantingProxyService initialized, planting-service URL: ${plantingServiceUrl}`,
    );
  }

  async getOrders(params: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    status?: string;
    accountSequences?: string[];
  }) {
    try {
      const qp = new URLSearchParams();
      if (params.page) qp.append('page', params.page.toString());
      if (params.pageSize) qp.append('pageSize', params.pageSize.toString());
      if (params.keyword) qp.append('keyword', params.keyword);
      if (params.status) qp.append('status', params.status);
      if (params.accountSequences?.length) qp.append('accountSequences', params.accountSequences.join(','));

      const url = `/api/v1/internal/pre-planting/admin/orders?${qp.toString()}`;
      this.logger.debug(`[getOrders] 请求: ${url}`);
      const response = await this.httpClient.get(url);
      return response.data;
    } catch (error) {
      this.logger.error(`[getOrders] 失败: ${error.message}`);
      return { items: [], total: 0, page: params.page ?? 1, pageSize: params.pageSize ?? 20 };
    }
  }

  async getPositions(params: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    accountSequences?: string[];
  }) {
    try {
      const qp = new URLSearchParams();
      if (params.page) qp.append('page', params.page.toString());
      if (params.pageSize) qp.append('pageSize', params.pageSize.toString());
      if (params.keyword) qp.append('keyword', params.keyword);
      if (params.accountSequences?.length) qp.append('accountSequences', params.accountSequences.join(','));

      const url = `/api/v1/internal/pre-planting/admin/positions?${qp.toString()}`;
      this.logger.debug(`[getPositions] 请求: ${url}`);
      const response = await this.httpClient.get(url);
      return response.data;
    } catch (error) {
      this.logger.error(`[getPositions] 失败: ${error.message}`);
      return { items: [], total: 0, page: params.page ?? 1, pageSize: params.pageSize ?? 20 };
    }
  }

  async getMerges(params: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    status?: string;
  }) {
    try {
      const qp = new URLSearchParams();
      if (params.page) qp.append('page', params.page.toString());
      if (params.pageSize) qp.append('pageSize', params.pageSize.toString());
      if (params.keyword) qp.append('keyword', params.keyword);
      if (params.status) qp.append('status', params.status);

      const url = `/api/v1/internal/pre-planting/admin/merges?${qp.toString()}`;
      this.logger.debug(`[getMerges] 请求: ${url}`);
      const response = await this.httpClient.get(url);
      return response.data;
    } catch (error) {
      this.logger.error(`[getMerges] 失败: ${error.message}`);
      return { items: [], total: 0, page: params.page ?? 1, pageSize: params.pageSize ?? 20 };
    }
  }

  async getStats() {
    try {
      const url = '/api/v1/internal/pre-planting/admin/stats';
      this.logger.debug(`[getStats] 请求: ${url}`);
      const response = await this.httpClient.get(url);
      return response.data;
    } catch (error) {
      this.logger.error(`[getStats] 失败: ${error.message}`);
      return {
        totalOrders: 0,
        totalPortions: 0,
        totalAmount: 0,
        totalMerges: 0,
        totalTreesMerged: 0,
        totalUsers: 0,
        pendingContracts: 0,
      };
    }
  }
}
