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

import com.paypal.sdk.Environment;
import com.paypal.sdk.PaypalServerSdkClient;
import com.paypal.sdk.authentication.ClientCredentialsAuthModel;
import com.paypal.sdk.models.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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;
import org.springframework.web.client.RestTemplate;
import org.wfc.common.core.domain.R;
import org.wfc.common.core.utils.AESUtil;
import org.wfc.payment.domain.PayPalBean;
import org.wfc.payment.pay.paypal.service.IPayPalService;

import javax.annotation.Resource;

@Slf4j
@RestController
public class PayPalController {

	@Resource
	private PayPalBean payPalBean;

	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	@Bean
    public PaypalServerSdkClient paypalClient() {
        return new PaypalServerSdkClient.Builder()
//                .loggingConfig(builder -> builder
//                        .level(Level.DEBUG)
//                        .requestConfig(logConfigBuilder -> logConfigBuilder.body(true))
//                        .responseConfig(logConfigBuilder -> logConfigBuilder.headers(true)))
                .httpClientConfig(configBuilder -> configBuilder
                        .timeout(0))
                .environment(payPalBean.getSandBox() ? Environment.SANDBOX : Environment.PRODUCTION)
                .clientCredentialsAuth(new ClientCredentialsAuthModel.Builder(
						payPalBean.getClientId(),
						payPalBean.getClientSecret())
                        .build())
                .build();
    }


	@RestController
	@RequestMapping("/paypal")
	public class CheckoutController {

		@Resource
		private IPayPalService payPalService;

		@PostMapping("/orders")
		public R<Order> createOrder(@RequestParam Long orderId) {
			try {
//				String cart = objectMapper.writeValueAsString(request.get("cart"));
				Order response = payPalService.createOrder(orderId);
				return R.ok(response);
			} catch (Exception e) {
				log.error("Error creating paypal order", e);
				return R.fail(e.getMessage());
			}
		}

		@GetMapping("/result/one")
		public R<String> getPaypalConfig()
		{
			return R.ok(AESUtil.encrypt(payPalBean.getClientId()));
		}

		@PostMapping("/orders/{paypalOrderId}/capture/{orderId}")
		public R<Order> captureOrder(@PathVariable String paypalOrderId, @PathVariable Long orderId) {
			try {
				Order response = payPalService.captureOrders(paypalOrderId, orderId);
				return R.ok(response);
			} catch (Exception e) {
				log.error("Error creating paypal capture", e);
				return R.fail(e.getMessage());
			}
		}

	}
}
