package com.snack.server.module.order.controller;

import cn.hutool.core.util.StrUtil;
import com.snack.server.common.Result;
import com.snack.server.module.order.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 支付宝 / 微信支付回调（沙箱版）
 *
 * 真实生产：
 *   1. 支付宝 POST 异步通知到 /api/payment/alipay/notify
 *   2. 校验 sign 签名
 *   3. 解析 out_trade_no（订单号）、trade_no（支付宝交易号）
 *   4. 调用 OrderService.handlePaySuccess()
 *   5. 返回 "success" / "fail" 给支付宝
 *
 * 沙箱测试（手动调用）：
 *   POST /api/payment/alipay/notify
 *   ?orderId=1&payChannel=alipay&payTradeNo=20260601xxxx
 */
@Slf4j
@Tag(name = "支付回调（沙箱测试）")
@RestController
@RequestMapping("/api/payment")
@RequiredArgsConstructor
public class PaymentNotifyController {

    private final OrderService orderService;

    /**
     * 支付宝支付成功异步通知
     */
    @Operation(summary = "支付宝支付成功回调（沙箱测试用）")
    @PostMapping("/alipay/notify")
    public Result<String> alipayNotify(
            @RequestParam Long orderId,
            @RequestParam(required = false, defaultValue = "alipay") String payChannel,
            @RequestParam(required = false) String payTradeNo) {
        if (orderId == null) {
            return Result.fail(400, "orderId 不能为空");
        }
        if (StrUtil.isBlank(payTradeNo)) {
            payTradeNo = "ALIPAY-MOCK-" + System.currentTimeMillis();
        }
        log.info("收到支付宝支付回调 orderId={} payTradeNo={}", orderId, payTradeNo);
        boolean ok = orderService.handlePaySuccess(orderId, payChannel, payTradeNo);
        // 支付宝要求返回纯文本 "success" / "fail"，用 body 输出
        return ok ? Result.ok("success") : Result.fail("fail");
    }

    /**
     * 支付宝退款成功异步通知
     */
    @Operation(summary = "支付宝退款成功回调（沙箱测试用）")
    @PostMapping("/alipay/refund/notify")
    public Result<String> alipayRefundNotify(
            @RequestParam Long orderId,
            @RequestParam(required = false) String refundTradeNo) {
        if (orderId == null) {
            return Result.fail(400, "orderId 不能为空");
        }
        if (StrUtil.isBlank(refundTradeNo)) {
            refundTradeNo = "RF-MOCK-" + System.currentTimeMillis();
        }
        log.info("收到支付宝退款回调 orderId={} refundTradeNo={}", orderId, refundTradeNo);
        boolean ok = orderService.handleRefundSuccess(orderId, refundTradeNo);
        return ok ? Result.ok("success") : Result.fail("fail");
    }
}
