package repository

import (
	"bpmsapi/entity"
	"bpmsapi/util"
	"log"

	"github.com/jmoiron/sqlx"
)

type NotificationActions interface {
	SendOTP(mobno string) (string, error)
}

type NotificationRepository struct {
	db *sqlx.DB
}

// auth-jwt
func NotificationRepositoryInit(db *sqlx.DB) *NotificationRepository {
	return &NotificationRepository{
		db: db,
	}
}

func (notificationRepo *NotificationRepository) Begin() (*sqlx.Tx, error) {
	tx, err := notificationRepo.db.Beginx()
	if err != nil {
		return nil, err
	}
	return tx, nil
}

func (notificationRepo *NotificationRepository) SendOTP(mobileno string) (int, error) {
	otp := util.GenerateOTP()
	log.Println("NotificationRepository: SendOTP: sendingOTP: otp: ", otp)
	return otp, nil

}

func (notificationRepo *NotificationRepository) NotificationTokenUpdate(tx *sqlx.Tx, input entity.UpdateNotificationTokenInput) (string, error) {
	var err error
	var updateQuery string

	if input.IsEmployee == 1 {
		updateQuery = "UPDATE `BPMS_EMPLOYEE` SET `Notification_Token`= ? WHERE `Emp_Mobno` = ?"

	} else {
		updateQuery = "UPDATE `BPMS_USER` SET `Notification_Token`= ? WHERE `User_Mobno` = ?"
	}
	_, err = tx.Exec(updateQuery, input.Ntoken, input.Mobno)
	if err != nil {
		tx.Rollback()
		log.Println("NotificationRepository : NotificationTokenUpdate : updatingtoken : Error :", err.Error(), " : mobno :", input.Mobno)
		return "Error while updating the token ", err

	} else {
		mess := "Token updated successfully"
		log.Println("NotificationRepository : NotificationTokenUpdate : updatingtoken : mobno :", input.Mobno, ": message :")
		return mess, err
	}
}
