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

export interface AlipayPaymentResult {
  qrCodeUrl: string;
  tradeNo: string;
}

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

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

  /**
   * Create Alipay payment (QR code)
   */
  async createPayment(order: OrderEntity): Promise<AlipayPaymentResult> {
    // In production, use alipay-sdk to create actual payment
    // const alipay = new AlipaySdk({
    //   appId: this.configService.get('ALIPAY_APP_ID'),
    //   privateKey: this.configService.get('ALIPAY_PRIVATE_KEY'),
    // });
    //
    // const result = await alipay.exec('alipay.trade.precreate', {
    //   bizContent: {
    //     out_trade_no: order.id,
    //     total_amount: order.amount.toString(),
    //     subject: `iConsulting - ${order.serviceType} (${order.serviceCategory})`,
    //   },
    // });

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

    // Generate QR code as data URL
    const qrCodeDataUrl = await QRCode.toDataURL(mockPaymentUrl, {
      width: 256,
      margin: 2,
    });

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

    return {
      qrCodeUrl: qrCodeDataUrl,
      tradeNo: `ALIPAY_${Date.now()}`,
    };
  }

  /**
   * Handle Alipay callback
   */
  async handleCallback(payload: Record<string, unknown>): Promise<AlipayCallbackResult> {
    // In production, verify signature first
    // const isValid = this.verifySignature(payload);
    // if (!isValid) {
    //   throw new Error('Invalid Alipay callback signature');
    // }

    const orderId = payload.out_trade_no as string;
    const transactionId = payload.trade_no as string;
    const tradeStatus = payload.trade_status as string;

    console.log(`[Alipay] Callback received for order ${orderId}, status: ${tradeStatus}`);

    return {
      orderId,
      transactionId,
      success: tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED',
    };
  }

  /**
   * Verify callback signature
   */
  private verifySignature(_payload: Record<string, unknown>): boolean {
    // In production, implement actual signature verification
    // using alipay public key
    return true;
  }
}
