package tables

import (
	"Wine-Server/utils"
)

type RefundTable struct {
	Tid     string
	Manager string
	Time    utils.TimeType
	Cash    uint32
	Reason  string
}

func CreateRefundTable() error {
	SQL := "CREATE TABLE IF NOT EXISTS `refund`(" +
		"`tid` VARCHAR(32) PRIMARY KEY NOT NULL," +
		"`manager` VARCHAR(16) DEFAULT ''," +
		"`time` DATETIME DEFAULT CURRENT_TIMESTAMP," +
		"`cash` INT UNSIGNED DEFAULT 0," +
		"`reason` VARCHAR(128) DEFAULT '');"
	_, err := utils.Mysql.Exec(SQL)
	return err
}

func (row *RefundTable) Insert() error {
	SQL := "INSERT INTO `refund` (`tid`,`manager`,`cash`,`reason`) VALUES (?,?,?,?);"
	pre, err := utils.Mysql.Prepare(SQL)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Tid, row.Manager, row.Cash, row.Reason)
	return err
}

// Delete deprecated
func (row *RefundTable) Delete() error {
	SQL := utils.Format("DELETE FROM `refund` WHERE `id`='%s';", row.Tid)
	_, err := utils.Mysql.Exec(SQL)
	return err
}

func (row *RefundTable) Update(args utils.JsonType) error {
	keys, values := utils.UnZip(args)
	SQL := utils.Format("UPDATE `refund` SET %s WHERE `id`='%s';", utils.SqlFields(keys), row.Tid)
	pre, err := utils.Mysql.Prepare(SQL)
	if err != nil {
		return err
	}
	_, err = pre.Exec(values...)
	return err
}

func (row *RefundTable) UpdateSelf() error {
	SQL := "UPDATE `refund` SET `manager`=?,`time`=?,`cash`=?,`reason`=? WHERE `tid`=?;"
	pre, err := utils.Mysql.Prepare(SQL)
	if err != nil {
		return err
	}
	row.Time = utils.TimeNow()
	_, err = pre.Exec(row.Manager, row.Time, row.Cash, row.Reason, row.Tid)
	return err
}

func (row *RefundTable) Get() error {
	SQL := "SELECT `manager`,`time`,`cash`,`reason` FROM `refund` WHERE `tid`=?;"
	pre, err := utils.Mysql.Prepare(SQL)
	if err != nil {
		return err
	}
	err = pre.QueryRow(row.Tid).Scan(&row.Manager, &row.Time, &row.Cash, &row.Reason)
	return err
}
