import { Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

/**
 * 支付结果
 */
export interface PaymentResult {
  paymentId: string;
  orderId: string;
  qrCodeUrl?: string;
  paymentUrl?: string;
  expiresAt: string;
  method: string;
  amount: number;
}

/**
 * 订单信息
 */
export interface OrderInfo {
  id: string;
  userId: string;
  serviceType: string;
  serviceCategory?: string;
  conversationId?: string;
  amount: number;
  currency: string;
  status: string;
  paymentId?: string;
  paymentMethod?: string;
  paidAt?: string;
  completedAt?: string;
  createdAt: string;
  updatedAt: string;
}

/**
 * API 响应包装
 */
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

/**
 * Payment Service 客户端
 * 封装对 payment-service 的 HTTP 调用
 * 模式与 KnowledgeClientService 一致（native fetch）
 */
@Injectable()
export class PaymentClientService implements OnModuleInit {
  private baseUrl: string;

  constructor(private configService: ConfigService) {}

  onModuleInit() {
    this.baseUrl =
      this.configService.get<string>('PAYMENT_SERVICE_URL') ||
      'http://payment-service:3002';
    console.log(
      `[PaymentClient] Initialized with base URL: ${this.baseUrl}`,
    );
  }

  /**
   * 创建订单
   */
  async createOrder(params: {
    userId: string;
    serviceType: string;
    serviceCategory?: string;
    conversationId?: string;
  }): Promise<OrderInfo | null> {
    try {
      const response = await fetch(`${this.baseUrl}/orders`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-user-id': params.userId,
        },
        body: JSON.stringify({
          serviceType: params.serviceType,
          serviceCategory: params.serviceCategory,
          conversationId: params.conversationId,
        }),
      });

      if (!response.ok) {
        const errText = await response.text();
        console.error(
          `[PaymentClient] createOrder failed: ${response.status} ${errText}`,
        );
        return null;
      }

      const data = (await response.json()) as ApiResponse<OrderInfo>;
      return data.success ? data.data : null;
    } catch (error) {
      console.error('[PaymentClient] createOrder error:', error);
      return null;
    }
  }

  /**
   * 创建支付（生成二维码/支付链接）
   */
  async createPayment(params: {
    orderId: string;
    method: string;
  }): Promise<PaymentResult | null> {
    try {
      const response = await fetch(`${this.baseUrl}/payments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          orderId: params.orderId,
          method: params.method,
        }),
      });

      if (!response.ok) {
        const errText = await response.text();
        console.error(
          `[PaymentClient] createPayment failed: ${response.status} ${errText}`,
        );
        return null;
      }

      const data = (await response.json()) as ApiResponse<PaymentResult>;
      return data.success ? data.data : null;
    } catch (error) {
      console.error('[PaymentClient] createPayment error:', error);
      return null;
    }
  }

  /**
   * 查询支付状态
   */
  async checkPaymentStatus(
    paymentId: string,
  ): Promise<{ status: string; paidAt?: string } | null> {
    try {
      const response = await fetch(
        `${this.baseUrl}/payments/${paymentId}/status`,
      );

      if (!response.ok) {
        console.error(
          `[PaymentClient] checkPaymentStatus failed: ${response.status}`,
        );
        return null;
      }

      const data = (await response.json()) as ApiResponse<{
        status: string;
        paidAt?: string;
      }>;
      return data.success ? data.data : null;
    } catch (error) {
      console.error('[PaymentClient] checkPaymentStatus error:', error);
      return null;
    }
  }

  /**
   * 查询订单状态
   */
  async getOrderStatus(
    orderId: string,
  ): Promise<{
    orderId: string;
    status: string;
    paidAt?: string;
    completedAt?: string;
  } | null> {
    try {
      const response = await fetch(
        `${this.baseUrl}/orders/${orderId}/status`,
      );

      if (!response.ok) {
        console.error(
          `[PaymentClient] getOrderStatus failed: ${response.status}`,
        );
        return null;
      }

      const data = (await response.json()) as ApiResponse<{
        orderId: string;
        status: string;
        paidAt?: string;
        completedAt?: string;
      }>;
      return data.success ? data.data : null;
    } catch (error) {
      console.error('[PaymentClient] getOrderStatus error:', error);
      return null;
    }
  }

  /**
   * 查询用户订单列表
   */
  async getUserOrders(userId: string): Promise<OrderInfo[]> {
    try {
      const response = await fetch(`${this.baseUrl}/orders`, {
        headers: { 'x-user-id': userId },
      });

      if (!response.ok) {
        console.error(
          `[PaymentClient] getUserOrders failed: ${response.status}`,
        );
        return [];
      }

      const data = (await response.json()) as ApiResponse<OrderInfo[]>;
      return data.success ? data.data : [];
    } catch (error) {
      console.error('[PaymentClient] getUserOrders error:', error);
      return [];
    }
  }

  /**
   * 获取单个订单详情
   */
  async getOrderDetail(orderId: string): Promise<OrderInfo | null> {
    try {
      const response = await fetch(`${this.baseUrl}/orders/${orderId}`);

      if (!response.ok) {
        console.error(
          `[PaymentClient] getOrderDetail failed: ${response.status}`,
        );
        return null;
      }

      const data = (await response.json()) as ApiResponse<OrderInfo>;
      return data.success ? data.data : null;
    } catch (error) {
      console.error('[PaymentClient] getOrderDetail error:', error);
      return null;
    }
  }

  /**
   * 取消订单（仅限未支付的订单）
   */
  async cancelOrder(
    orderId: string,
  ): Promise<{ orderId: string; status: string } | null> {
    try {
      const response = await fetch(
        `${this.baseUrl}/orders/${orderId}/cancel`,
        { method: 'POST' },
      );

      if (!response.ok) {
        const errText = await response.text();
        console.error(
          `[PaymentClient] cancelOrder failed: ${response.status} ${errText}`,
        );
        return null;
      }

      const data = (await response.json()) as ApiResponse<{
        orderId: string;
        status: string;
      }>;
      return data.success ? data.data : null;
    } catch (error) {
      console.error('[PaymentClient] cancelOrder error:', error);
      return null;
    }
  }
}
