/**
 * 合同管理服务
 * [2026-02-05] 新增：调用 planting-service 内部 API 获取合同数据
 * 回滚方式：删除此文件并从 app.module.ts 中移除引用
 */

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

/**
 * 合同 DTO
 */
export interface ContractDto {
  orderNo: string;
  contractNo: string;
  userId: string;
  accountSequence: string;
  userRealName: string | null;
  userPhoneNumber: string | null;
  treeCount: number;
  totalAmount: number;
  provinceCode: string;
  provinceName: string;
  cityCode: string;
  cityName: string;
  status: string;
  signedAt: string | null;
  signedPdfUrl: string | null;
  createdAt: string;
}

/**
 * 合同列表响应
 */
export interface ContractsListResponse {
  items: ContractDto[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

/**
 * 合同统计响应
 */
export interface ContractStatisticsResponse {
  totalContracts: number;
  signedContracts: number;
  pendingContracts: number;
  expiredContracts: number;
}

/**
 * 合同查询参数
 */
export interface ContractQueryParams {
  accountSequences?: string[];
  signedAfter?: string;
  signedBefore?: string;
  provinceCode?: string;
  cityCode?: string;
  status?: string;
  page?: number;
  pageSize?: number;
  orderBy?: 'signedAt' | 'createdAt';
  orderDir?: 'asc' | 'desc';
}

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

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

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

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

  /**
   * 获取合同列表
   */
  async getContracts(params: ContractQueryParams): Promise<ContractsListResponse> {
    try {
      const queryParams = new URLSearchParams();

      if (params.accountSequences?.length) {
        queryParams.append('accountSequences', params.accountSequences.join(','));
      }
      if (params.signedAfter) queryParams.append('signedAfter', params.signedAfter);
      if (params.signedBefore) queryParams.append('signedBefore', params.signedBefore);
      if (params.provinceCode) queryParams.append('provinceCode', params.provinceCode);
      if (params.cityCode) queryParams.append('cityCode', params.cityCode);
      if (params.status) queryParams.append('status', params.status);
      if (params.page) queryParams.append('page', params.page.toString());
      if (params.pageSize) queryParams.append('pageSize', params.pageSize.toString());
      if (params.orderBy) queryParams.append('orderBy', params.orderBy);
      if (params.orderDir) queryParams.append('orderDir', params.orderDir);

      const url = `/api/v1/planting/internal/contracts?${queryParams.toString()}`;
      this.logger.debug(`[getContracts] 请求: ${url}`);

      const response = await this.httpClient.get<ContractsListResponse>(url);
      return response.data;
    } catch (error) {
      this.logger.error(`[getContracts] 失败: ${error.message}`);
      return {
        items: [],
        total: 0,
        page: params.page ?? 1,
        pageSize: params.pageSize ?? 50,
        totalPages: 0,
      };
    }
  }

  /**
   * 获取用户的合同列表
   */
  async getUserContracts(accountSequence: string, params?: {
    page?: number;
    pageSize?: number;
  }): Promise<ContractsListResponse> {
    return this.getContracts({
      accountSequences: [accountSequence],
      page: params?.page,
      pageSize: params?.pageSize,
      status: undefined, // 查询所有状态
    });
  }

  /**
   * 获取单个合同详情
   */
  async getContract(orderNo: string): Promise<ContractDto | null> {
    try {
      const url = `/api/v1/planting/internal/contracts/${orderNo}`;
      this.logger.debug(`[getContract] 请求: ${url}`);

      const response = await this.httpClient.get<ContractDto>(url);
      return response.data;
    } catch (error) {
      if (error.response?.status === 404) {
        return null;
      }
      this.logger.error(`[getContract] 失败: ${error.message}`);
      throw error;
    }
  }

  /**
   * 下载合同 PDF
   * @returns PDF Buffer
   */
  async downloadContractPdf(orderNo: string): Promise<Buffer> {
    const url = `/api/v1/planting/internal/contracts/${orderNo}/pdf`;
    this.logger.debug(`[downloadContractPdf] 请求: ${url}`);

    const response = await this.httpClient.get(url, {
      responseType: 'arraybuffer',
    });

    return Buffer.from(response.data);
  }

  /**
   * 获取合同统计信息
   */
  async getStatistics(params?: {
    provinceCode?: string;
    cityCode?: string;
  }): Promise<ContractStatisticsResponse> {
    try {
      const queryParams = new URLSearchParams();
      if (params?.provinceCode) queryParams.append('provinceCode', params.provinceCode);
      if (params?.cityCode) queryParams.append('cityCode', params.cityCode);

      const url = `/api/v1/planting/internal/contracts/statistics?${queryParams.toString()}`;
      this.logger.debug(`[getStatistics] 请求: ${url}`);

      const response = await this.httpClient.get<ContractStatisticsResponse>(url);
      return response.data;
    } catch (error) {
      this.logger.error(`[getStatistics] 失败: ${error.message}`);
      return {
        totalContracts: 0,
        signedContracts: 0,
        pendingContracts: 0,
        expiredContracts: 0,
      };
    }
  }
}
