package mysqlkindboxreq

import (
	"context"

	"git.gocasts.ir/ebhomengo/niki/entity"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
)

func (d *DB) AddKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error) {
	const op = "mysqlkindboxreq.AddKindBoxReq"

	query := `insert into kind_box_reqs(benefactor_id,kind_box_type,deliver_address_id,count_requested,deliver_refer_date,deliver_refer_time_id,status) values (?,?,?,?,?,?,?)`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyKindBoxReqAdd, query)
	if err != nil {
		return entity.KindBoxReq{}, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	res, err := stmt.ExecContext(ctx,
		kindBoxReq.BenefactorID, kindBoxReq.KindBoxType,
		kindBoxReq.DeliverAddressID, kindBoxReq.CountRequested, kindBoxReq.DeliverReferDate,
		kindBoxReq.DeliverReferTimeID, kindBoxReq.Status)
	if err != nil {
		return entity.KindBoxReq{}, richerror.New(op).WithErr(err).
			WithKind(richerror.KindUnexpected)
	}

	//nolint
	// err is always nil
	id, _ := res.LastInsertId()
	kindBoxReq.ID = uint(id)

	return kindBoxReq, nil
}
