import axios from 'axios';
import { Injectable } from '@nestjs/common';
import { ConfigurationService } from '../../config/configuration.service';

@Injectable()
export class ZarinpalService {
  private axios;
  private redirectUrl;

  constructor(private config: ConfigurationService) {
    this.axios = axios.create({
      baseURL:
        config.gateway.zarinpalMode === 'sandbox'
          ? 'https://sandbox.zarinpal.com/pg/rest/WebGate'
          : 'https://www.zarinpal.com/pg/rest/WebGate',
    });

    this.redirectUrl =
      config.gateway.zarinpalMode === 'sandbox'
        ? 'https://sandbox.zarinpal.com/pg/StartPay'
        : 'https://www.zarinpal.com/pg/StartPay';
  }

  /**
   * @param amount Amount on Toman
   */
  async paymentRequest(
    amount,
    callbackURL,
    description = '',
    email = '',
    mobile = '',
  ) {
    const { data } = await this.axios.post('/PaymentRequest.json', {
      MerchantID: this.config.gateway.zarinpalMerchantId,
      Amount: amount, // Toman
      CallbackURL: callbackURL,
      Description: description,
      Email: email,
      Mobile: mobile,
    });

    if (data.Status !== 100) {
      throw new Error('اتصال به درگاه برقرار نشد، لطفا مجدد تلاش کنید');
    }

    return {
      code: data.Status,
      message: '',
      authority: data.Authority,
      url: `${this.redirectUrl}/${data.Authority}`,
    };
  }

  /**
   * @param amount Amount on Toman
   */
  async paymentVerification(authority, amount) {
    const { data } = await this.axios.post('/PaymentVerification.json', {
      MerchantID: this.config.gateway.zarinpalMerchantId,
      Amount: amount,
      Authority: authority,
    });

    if (data.Status !== 100 && data.Status != 101) {
      throw 'خطایی رخ داده است، با پشتیبانی 09391857423 تماس حاصل فرمایید';
    }

    return {
      code: data.Status,
      message: '',
      referenceNumber: data.RefID,
    };
  }
}
