package shop.alien.store.controller;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import shop.alien.entity.result.R;
import shop.alien.store.strategy.payment.PaymentStrategyFactory;
import shop.alien.util.common.constant.PaymentEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = {"支付宝服务商支付接口"})
@CrossOrigin
@RestController
@RequestMapping("/alipayPartnerPayment")
@RequiredArgsConstructor
public class AlipayPartnerPaymentController {

    private final PaymentStrategyFactory paymentStrategyFactory;

    /**
     * 支付宝支付回调通知接口
     * 异步回调地址状态码 (http 状态码) 为 200 时表示异步通知成功，返回码为 404 或 500 时则表示服务器内部错误，需要商家自行排查。
     * @param notifyData 回调 JSON 报文
     * @return 204 无 body 或 5XX + 失败报文
     */
    /**
     * 服务商模式支付宝支付回调（与直连支付宝回调分离，需在商户平台配置 notify_url 指向本地址）
     */
    @RequestMapping("/alipayPartnerNotify")
    public ResponseEntity<?> alipayPartnerNotify(@RequestBody String notifyData, HttpServletRequest request) throws Exception {
        log.info("[支付宝服务商回调] 收到请求, Content-Length={}, Alipay-Serial={}",
                request.getContentLength(), request.getHeader("Alipay-Serial"));
        try {
            R result = paymentStrategyFactory.getStrategy(PaymentEnum.ALIPAY_PARTNER.getType()).handleNotify(notifyData);
            if (R.isSuccess(result)) {
                return ResponseEntity.noContent().build();
            }
            String message = result.getMsg() != null ? result.getMsg() : "失败";
            Map<String, String> failBody = new HashMap<>(2);
            failBody.put("code", "FAIL");
            failBody.put("message", message);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failBody);
        } catch (Exception e) {
            log.error("[支付宝服务商回调] 处理异常", e);
            String msg = e.getMessage() != null ? e.getMessage() : "失败";
            Map<String, String> failBody = new HashMap<>(2);
            failBody.put("code", "FAIL");
            failBody.put("message", msg);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failBody);
        }
    }
}
