package mysqlkindboxreq

import (
	"context"
	"database/sql"
	"time"

	"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) UpdateKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) error {
	const op = "mysqlkindboxreq.UpdateKindBoxReq"

	var (
		senderAgentID sql.NullInt64
		deliveredAt   sql.NullTime
	)
	if kindBoxReq.SenderAgentID != 0 {
		senderAgentID = sql.NullInt64{Int64: int64(kindBoxReq.SenderAgentID), Valid: true}
	} else {
		senderAgentID = sql.NullInt64{Int64: 0, Valid: false}
	}
	if !kindBoxReq.DeliveredAt.IsZero() {
		deliveredAt = sql.NullTime{Time: kindBoxReq.DeliveredAt, Valid: true}
	} else {
		deliveredAt = sql.NullTime{Time: time.Time{}, Valid: false}
	}

	query := `UPDATE kind_box_reqs
			  SET benefactor_id = ?, kind_box_type = ?, count_requested = ?, count_accepted = ?,
			      description = ?, status = ?, deliver_refer_time_id = ?, deliver_refer_date = ?,
			      deliver_address_id = ?, sender_agent_id = ?, delivered_at = ? 
			  WHERE id = ? AND deleted_at IS NULL`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyKindBoxReqUpdate, query)
	if err != nil {
		return richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	_, uErr := stmt.ExecContext(ctx, kindBoxReq.BenefactorID, kindBoxReq.KindBoxType,
		kindBoxReq.CountRequested, kindBoxReq.CountAccepted, kindBoxReq.Description, kindBoxReq.Status,
		kindBoxReq.DeliverReferTimeID, kindBoxReq.DeliverReferDate, kindBoxReq.DeliverAddressID,
		senderAgentID, deliveredAt, kindBoxReq.ID)
	if uErr != nil {
		return richerror.New(op).WithErr(uErr).WithMessage(errmsg.ErrorMsgCantUpdateRecord).
			WithKind(richerror.KindUnexpected)
	}

	return nil
}
