package com.gxwebsoft.payment.controller;

import com.gxwebsoft.payment.constants.PaymentConstants;
import com.gxwebsoft.payment.enums.PaymentType;
import com.gxwebsoft.payment.exception.PaymentException;
import com.gxwebsoft.payment.service.PaymentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一支付回调控制器
 * 处理所有支付方式的异步通知回调
 *
 * @author 科技小王子
 * @since 2025-01-26
 */
@Slf4j
@Tag(name = "统一支付回调接口", description = "处理所有支付方式的异步通知回调")
@RestController
@RequestMapping("/api/payment/notify")
public class PaymentNotifyController {

    @Resource
    private PaymentService paymentService;

    @Operation(summary = "微信支付回调通知", description = "处理微信支付的异步通知")
    @PostMapping("/wechat/{tenantId}")
    public String wechatNotify(
            @Parameter(description = "租户ID", required = true)
            @PathVariable("tenantId") Integer tenantId,
            @RequestBody String body,
            HttpServletRequest request) {
        
        log.info("收到微信支付回调通知, 租户ID: {}", tenantId);
        
        try {
            // 提取请求头
            Map<String, String> headers = extractHeaders(request);
            
            // 处理回调
            String result = paymentService.handlePaymentNotify(PaymentType.WECHAT_NATIVE, headers, body, tenantId);
            
            log.info("微信支付回调处理完成, 租户ID: {}, 结果: {}", tenantId, result);
            return result;
            
        } catch (PaymentException e) {
            log.error("微信支付回调处理失败, 租户ID: {}, 错误: {}", tenantId, e.getMessage());
            return PaymentConstants.Wechat.NOTIFY_FAIL;
        } catch (Exception e) {
            log.error("微信支付回调系统错误, 租户ID: {}, 错误: {}", tenantId, e.getMessage(), e);
            return PaymentConstants.Wechat.NOTIFY_FAIL;
        }
    }

    @Operation(summary = "支付宝支付回调通知", description = "处理支付宝支付的异步通知")
    @PostMapping("/alipay/{tenantId}")
    public String alipayNotify(
            @Parameter(description = "租户ID", required = true)
            @PathVariable("tenantId") Integer tenantId,
            @RequestBody String body,
            HttpServletRequest request) {
        
        log.info("收到支付宝支付回调通知, 租户ID: {}", tenantId);
        
        try {
            // 提取请求头
            Map<String, String> headers = extractHeaders(request);
            
            // 处理回调
            String result = paymentService.handlePaymentNotify(PaymentType.ALIPAY, headers, body, tenantId);
            
            log.info("支付宝支付回调处理完成, 租户ID: {}, 结果: {}", tenantId, result);
            return result;
            
        } catch (PaymentException e) {
            log.error("支付宝支付回调处理失败, 租户ID: {}, 错误: {}", tenantId, e.getMessage());
            return PaymentConstants.Alipay.NOTIFY_FAIL;
        } catch (Exception e) {
            log.error("支付宝支付回调系统错误, 租户ID: {}, 错误: {}", tenantId, e.getMessage(), e);
            return PaymentConstants.Alipay.NOTIFY_FAIL;
        }
    }

    @Operation(summary = "银联支付回调通知", description = "处理银联支付的异步通知")
    @PostMapping("/unionpay/{tenantId}")
    public String unionPayNotify(
            @Parameter(description = "租户ID", required = true)
            @PathVariable("tenantId") Integer tenantId,
            @RequestBody String body,
            HttpServletRequest request) {
        
        log.info("收到银联支付回调通知, 租户ID: {}", tenantId);
        
        try {
            // 提取请求头
            Map<String, String> headers = extractHeaders(request);
            
            // 处理回调
            String result = paymentService.handlePaymentNotify(PaymentType.UNION_PAY, headers, body, tenantId);
            
            log.info("银联支付回调处理完成, 租户ID: {}, 结果: {}", tenantId, result);
            return result;
            
        } catch (PaymentException e) {
            log.error("银联支付回调处理失败, 租户ID: {}, 错误: {}", tenantId, e.getMessage());
            return "failure";
        } catch (Exception e) {
            log.error("银联支付回调系统错误, 租户ID: {}, 错误: {}", tenantId, e.getMessage(), e);
            return "failure";
        }
    }

    @Operation(summary = "通用支付回调通知", description = "处理指定支付类型的异步通知")
    @PostMapping("/{paymentType}/{tenantId}")
    public String genericNotify(
            @Parameter(description = "支付类型", required = true)
            @PathVariable("paymentType") PaymentType paymentType,
            @Parameter(description = "租户ID", required = true)
            @PathVariable("tenantId") Integer tenantId,
            @RequestBody String body,
            HttpServletRequest request) {
        
        log.info("收到{}支付回调通知, 租户ID: {}", paymentType.getName(), tenantId);
        
        try {
            // 提取请求头
            Map<String, String> headers = extractHeaders(request);
            
            // 处理回调
            String result = paymentService.handlePaymentNotify(paymentType, headers, body, tenantId);
            
            log.info("{}支付回调处理完成, 租户ID: {}, 结果: {}", paymentType.getName(), tenantId, result);
            return result;
            
        } catch (PaymentException e) {
            log.error("{}支付回调处理失败, 租户ID: {}, 错误: {}", paymentType.getName(), tenantId, e.getMessage());
            return getFailureResponse(paymentType);
        } catch (Exception e) {
            log.error("{}支付回调系统错误, 租户ID: {}, 错误: {}", paymentType.getName(), tenantId, e.getMessage(), e);
            return getFailureResponse(paymentType);
        }
    }

    /**
     * 提取HTTP请求头
     */
    private Map<String, String> extractHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>();
        
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headers.put(headerName, headerValue);
        }
        
        // 记录关键头部信息（不记录敏感信息）
        log.debug("提取请求头完成, 头部数量: {}", headers.size());
        
        return headers;
    }

    /**
     * 根据支付类型获取失败响应
     */
    private String getFailureResponse(PaymentType paymentType) {
        switch (paymentType) {
            case WECHAT:
            case WECHAT_NATIVE:
                return PaymentConstants.Wechat.NOTIFY_FAIL;
            case ALIPAY:
                return PaymentConstants.Alipay.NOTIFY_FAIL;
            case UNION_PAY:
                return "failure";
            default:
                return "fail";
        }
    }
}
