import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as QRCode from 'qrcode';
import { OrderEntity } from '../../../domain/entities/order.entity';

export interface WechatPaymentResult {
  qrCodeUrl: string;
  prepayId: string;
}

export interface WechatCallbackResult {
  orderId: string;
  transactionId: string;
  success: boolean;
}

@Injectable()
export class WechatPayAdapter {
  constructor(private configService: ConfigService) {}

  /**
   * Create WeChat Pay payment (Native QR code)
   */
  async createPayment(order: OrderEntity): Promise<WechatPaymentResult> {
    // In production, use wechat pay API
    // const result = await this.wechatPayClient.transactions_native({
    //   description: `iConsulting - ${order.serviceType}`,
    //   out_trade_no: order.id,
    //   notify_url: this.configService.get('WECHAT_NOTIFY_URL'),
    //   amount: {
    //     total: Math.round(order.amount * 100), // Convert to cents
    //     currency: 'CNY',
    //   },
    // });

    // For development, generate a mock QR code
    const mockPaymentUrl = `weixin://wxpay/bizpayurl?orderId=${order.id}&amount=${order.amount}`;

    const qrCodeDataUrl = await QRCode.toDataURL(mockPaymentUrl, {
      width: 256,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#ffffff',
      },
    });

    console.log(`[WeChatPay] Created payment for order ${order.id}, amount: ${order.amount}`);

    return {
      qrCodeUrl: qrCodeDataUrl,
      prepayId: `WECHAT_${Date.now()}`,
    };
  }

  /**
   * Handle WeChat Pay callback
   */
  async handleCallback(payload: Record<string, unknown>): Promise<WechatCallbackResult> {
    // In production:
    // 1. Verify signature
    // 2. Decrypt notification body
    // 3. Process payment result

    const resource = payload.resource as Record<string, unknown> | undefined;

    // Mock parsing for development
    const orderId = (resource?.out_trade_no as string) || (payload.out_trade_no as string);
    const transactionId = (resource?.transaction_id as string) || (payload.transaction_id as string);
    const tradeState = (resource?.trade_state as string) || (payload.trade_state as string);

    console.log(`[WeChatPay] Callback received for order ${orderId}, state: ${tradeState}`);

    return {
      orderId,
      transactionId,
      success: tradeState === 'SUCCESS',
    };
  }
}
