package repository

import (
	"bpmsapi/dto"
	"bpmsapi/entity"
	"bpmsapi/util"
	"errors"
	"fmt"
	"log"
	"strings"

	"github.com/jmoiron/sqlx"
	razorpay "github.com/razorpay/razorpay-go"
)

type PaymentActions interface {
	GetOnlinePaymentId(input entity.CreateOnlinePaymentIdInput, data map[string]interface{}) (map[string]interface{}, error)
}

type PaymentRepository struct {
	tx *sqlx.Tx
}

func PaymentRepositoryInit(tx *sqlx.Tx) *PaymentRepository {
	return &PaymentRepository{
		tx: tx,
	}
}

func (paymentRepo *PaymentRepository) GetOnlinePaymentId(input entity.CreateOnlinePaymentIdInput, data map[string]interface{}) (map[string]interface{}, error) {
	config, _ := util.LoadConfiguration()
	fmt.Println(config.Razorpay.Apikey, config.Razorpay.Apisecret)
	client := razorpay.NewClient(config.Razorpay.Apikey, config.Razorpay.Apisecret)
	resp, err := client.Order.Create(data, nil)
	if err != nil {
		log.Println("PaymentRepository: GetOnlinePaymentId: srq_id:", input.ReceiptNo, " Error:", err.Error())
		return nil, err
	} else {
		razorpayId := resp["id"].(string)
		status := resp["status"].(string)
		if strings.ToLower(status) == "created" {
			insQuery := "INSERT INTO `BPMS_PAYMENT`( `Srq_Payment_Id`, `Srq_Id`, `Amount`, `Payment_Status`) VALUES (?,?,?,?)"
			_, err := paymentRepo.tx.Exec(insQuery, razorpayId, input.ReceiptNo, input.Total_Amount, status)
			if err != nil {
				paymentRepo.tx.Rollback()
				log.Println("PaymentRepository: GetOnlinePaymentId: insertingpaymentinfo:  :Error: ", err.Error())
				return nil, err
			}
			return resp, nil
		} else {
			log.Println("PaymentRepository: GetOnlinePaymentId: paymentstatus:  srq_id: ", input.ReceiptNo)
			return nil, errors.New(dto.CreatePaymentInvalidStatus)
		}

	}

}
