import { WechatPayEndpoints } from "../../../../constants/wechat-pay-endpoints.const";
import { TokenType, DebugLevel } from "../../../../enums";
import { SecurepayConstruction } from "../../../../interfaces/common/construction.interface";
import { WechatPayInitialResponse } from "../../../../interfaces/wechat-pay/wechat-pay-initial-response.interface";
import { WechatPayTransactionInitial } from "../../../../interfaces/wechat-pay/wechat-pay-transaction-initial.interface";
import { WechatPayTransactionRefund } from "../../../../interfaces/wechat-pay/wechat-pay-transaction-refund.interface";
import { RequestService } from "../../../common/request/request.service";
import { WechatPayObject } from "../../../../interfaces/wechat-pay/wechat-pay-object.interface";

export class WechatPayTransactionService {

  /** Services */
  private _http: RequestService;

  /** Variables */
  private sandbox      : boolean;
  private debugLevel   : DebugLevel;
  private clientId     : string;
  private clientSecret : string;
  private merchantCode : string;
  
  constructor(options: SecurepayConstruction) {
    this._http        = new RequestService(options);
    this.sandbox      = options.sandbox    || false;
    this.debugLevel   = options.debugLevel || DebugLevel.NONE;
    this.clientId     = options.clientId;
    this.clientSecret = options.clientSecret;
    this.merchantCode = options.merchantCode;
  }

  /**
   * Initiates a Wechat transaction.
   * 
   * @param {WechatPayTransactionInitial} payload
   */
  initialTransaction(payload: WechatPayTransactionInitial): Promise<WechatPayInitialResponse> {
    if (!payload.merchantCode)
      payload.merchantCode = this.merchantCode;
    return this._http.post({
      url: WechatPayEndpoints.INITIAL(this.sandbox),
      token_type: TokenType.SECUREPAY_JWT,
      data: payload
    })
  }

  /**
   * Refunds a previously executed Wechat transaction
   * 
   * @param {string} orderId
   * @param {WechatPayTransactionRefund} payload
   */
  refundTransaction(orderId: string, payload: WechatPayTransactionRefund) {
    if (!payload.merchantCode)
      payload.merchantCode = this.merchantCode;
    return this._http.post({
      url: WechatPayEndpoints.REFUND(this.sandbox, orderId),
      token_type: TokenType.SECUREPAY_JWT,
      data: payload
    })
  }

  /**
   * Retrieves billing & shipping details for a customer that has previously initiated a Wechat transaction
   * 
   * @param {string} orderId
   * @param {string} merchantCode
   */
  retrieveTransaction(orderId: string, merchantCode?: string): Promise<WechatPayObject> {
    if (!merchantCode)
        merchantCode = this.merchantCode;
    return this._http.get({
      url: WechatPayEndpoints.RETRIEVE(this.sandbox, orderId, merchantCode),
      token_type: TokenType.SECUREPAY_JWT
    })
  }
}