import { Controller, Post, Body, Headers, HttpCode, HttpStatus, Logger, RawBodyRequest, Req } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiExcludeEndpoint } from '@nestjs/swagger';
import { PaymentService } from './payment.service';
import { Request } from 'express';

@ApiTags('支付回调')
@Controller('app/payment')
export class PaymentController {
  private readonly logger = new Logger(PaymentController.name);

  constructor(private readonly paymentService: PaymentService) {}

  @Post('wechat/notify')
  @HttpCode(HttpStatus.OK)
  @ApiExcludeEndpoint()
  async wechatNotify(
    @Req() req: RawBodyRequest<Request>,
    @Headers('wechatpay-signature') signature: string,
    @Headers('wechatpay-timestamp') timestamp: string,
    @Headers('wechatpay-nonce') nonce: string,
    @Headers('wechatpay-serial') serial: string,
    @Body() body: any,
  ) {
    this.logger.log('收到微信支付回调');

    try {
      // 获取原始请求体
      const rawBody = req.rawBody ? req.rawBody.toString('utf8') : JSON.stringify(body);

      // 验证签名
      const isValid = await this.paymentService.verifyWechatSignature({
        timestamp,
        nonce,
        body: rawBody,
        signature,
        serial,
      });

      if (!isValid) {
        this.logger.error('微信支付回调签名验证失败');
        return { code: 'FAIL', message: '签名验证失败' };
      }

      // 处理回调
      await this.paymentService.handleWechatNotify(body);

      return { code: 'SUCCESS', message: '成功' };
    } catch (error) {
      this.logger.error(`处理微信支付回调失败: ${error.message}`, error.stack);
      return { code: 'FAIL', message: error.message };
    }
  }

  @Post('wechat/refund-notify')
  @HttpCode(HttpStatus.OK)
  @ApiExcludeEndpoint()
  async wechatRefundNotify(
    @Req() req: RawBodyRequest<Request>,
    @Headers('wechatpay-signature') signature: string,
    @Headers('wechatpay-timestamp') timestamp: string,
    @Headers('wechatpay-nonce') nonce: string,
    @Headers('wechatpay-serial') serial: string,
    @Body() body: any,
  ) {
    this.logger.log('收到微信退款回调');

    try {
      const rawBody = req.rawBody ? req.rawBody.toString('utf8') : JSON.stringify(body);

      const isValid = await this.paymentService.verifyWechatSignature({
        timestamp,
        nonce,
        body: rawBody,
        signature,
        serial,
      });

      if (!isValid) {
        this.logger.error('微信退款回调签名验证失败');
        return { code: 'FAIL', message: '签名验证失败' };
      }

      await this.paymentService.handleWechatRefundNotify(body);

      return { code: 'SUCCESS', message: '成功' };
    } catch (error) {
      this.logger.error(`处理微信退款回调失败: ${error.message}`, error.stack);
      return { code: 'FAIL', message: error.message };
    }
  }
}
