package org.wfc.payment.pay.ccpay.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.wfc.payment.pay.ccpay.model.PaymentRequest;
import org.wfc.payment.pay.ccpay.model.PaymentResponse;
import org.wfc.payment.pay.ccpay.model.UCreditCardToken;
import org.wfc.payment.pay.ccpay.model.RefundResponse;
import org.wfc.payment.pay.ccpay.model.RefundRequest;
import org.wfc.payment.pay.ccpay.service.IUCreditCardOrderService;
import org.wfc.payment.pay.ccpay.service.IUCreditCardTokenService;

/**
 * Credit card payment controller
 * 
 */
@RestController
@RequestMapping("/ccpay")
public class CcpayController {

    private final IUCreditCardOrderService paymentService;
    private final IUCreditCardTokenService tokenService;

    @Autowired
    public CcpayController(IUCreditCardOrderService paymentService, IUCreditCardTokenService tokenService) {
        this.paymentService = paymentService;
        this.tokenService = tokenService;
    }

    @PostMapping("/payOrder")
    public ResponseEntity<PaymentResponse> processPayment(@RequestBody PaymentRequest paymentRequest) {
        // 检查用户是否已有支付令牌
        UCreditCardToken token = tokenService.getTokenByUserId(paymentRequest.getUserId());
        if (token != null) {
            // 使用支付令牌进行支付
            paymentRequest.setToken(token.getToken());
        } else {
            // 用户首次支付，获取支付令牌并存储
            String newToken = paymentService.getPaymentToken(paymentRequest);
            token = new UCreditCardToken();
            token.setUserId(paymentRequest.getUserId());
            token.setToken(newToken);
            token.setCardLastFour(paymentRequest.getCardLastFour());
            token.setCardType(paymentRequest.getCardType());
            tokenService.saveToken(token);
            paymentRequest.setToken(newToken);
        }

        PaymentResponse processedPayment = paymentService.processPayment(paymentRequest);
        return ResponseEntity.ok(processedPayment);
    }

    @GetMapping("/queryOrder/{orderId}")
    public ResponseEntity<PaymentResponse> queryOrder(@PathVariable Long orderId) {
        PaymentResponse paymentResponse = paymentService.queryOrder(orderId);
        return ResponseEntity.ok(paymentResponse);
    }

    @PostMapping("/refundOrder")
    public ResponseEntity<RefundResponse> refundOrder(@RequestBody RefundRequest refundRequest) {
        RefundResponse refundResponse = paymentService.refundOrder(refundRequest);
        return ResponseEntity.ok(refundResponse);
    }    
}