package coingate

import (
	"errors"
	"fmt"
	"go-admin/common/global"
	"go-admin/common/helper"
	"go-admin/config"
	"go-admin/models/coingatedto"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/bytedance/sonic"

	log "github.com/go-admin-team/go-admin-core/logger"
)

/*
获取支付连接

  - @endPoint basic url
  - @token api 密钥
  - @req 请求参数
*/
func GetPaymentUrl(endPoint string, token string, req *coingatedto.OrderRequest) (resp coingatedto.OrderResponse, err error) {
	method := "POST"
	url := fmt.Sprintf("%s%s", endPoint, "/v2/orders")
	payload, err := sonic.Marshal(req)

	if err != nil {
		return
	}
	client := &http.Client{}
	err = helper.CreateHtppProxy("", config.ExtConfig.ProxyUrl, client)

	if err != nil {
		return
	}

	request, err := http.NewRequest(method, url, strings.NewReader(string(payload)))

	if err != nil {
		fmt.Println(err)
		return
	}
	request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
	request.Header.Add("Content-Type", "application/json")

	res, err := client.Do(request)
	if err != nil {
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}

	if res.StatusCode != http.StatusOK {
		log.Error("status:", res.Status, "获取支付失败:", string(body))
		err = errors.New("获取支付连接失败,status:" + res.Status)
		return
	}

	err = sonic.Unmarshal(body, &resp)

	return
}

/*
支付回调
*/
func CallBack(req *coingatedto.OrderCallBackResponse) error {
	switch req.Status {
	case global.COINGATE_STATUS_NEW:
	case global.COINGATE_STATUS_PENDING:
	case global.COINGATE_STATUS_CONFIRMING:
	case global.COINGATE_STATUS_PAID:
	case global.COINGATE_STATUS_INVALID:
	case global.COINGATE_STATUS_EXPIRED:
	case global.COINGATE_STATUS_CANCELED:
	case global.COINGATE_STATUS_REFUNDED:
	case global.COINGATE_STATUS_PARTIALLY_REFUNDED:
	default:
		errStr := fmt.Sprintf("支付回调未找到状态%s", req.Status)
		log.Error(errStr)
		return errors.New(errStr)
	}

	return nil
}
