package mysqlkindbox

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) UpdateKindBox(ctx context.Context, kindBox entity.KindBox) error {
	const op = "mysqlkindbox.UpdateKindBox"

	// Handle nullable fields
	var (
		returnReferTimeID sql.NullInt64
		returnReferDate   sql.NullTime
		returnAddressID   sql.NullInt64
		receiverAgentID   sql.NullInt64
		returnedAt        sql.NullTime
	)

	if kindBox.ReturnReferTimeID != 0 {
		returnReferTimeID = sql.NullInt64{Int64: int64(kindBox.ReturnReferTimeID), Valid: true}
	} else {
		returnReferTimeID = sql.NullInt64{Int64: 0, Valid: false}
	}

	if !kindBox.ReturnReferDate.IsZero() {
		returnReferDate = sql.NullTime{Time: kindBox.ReturnReferDate, Valid: true}
	} else {
		returnReferDate = sql.NullTime{Time: time.Time{}, Valid: false}
	}

	if kindBox.ReturnAddressID != 0 {
		returnAddressID = sql.NullInt64{Int64: int64(kindBox.ReturnAddressID), Valid: true}
	} else {
		returnAddressID = sql.NullInt64{Int64: 0, Valid: false}
	}

	if kindBox.ReceiverAgentID != 0 {
		receiverAgentID = sql.NullInt64{Int64: int64(kindBox.ReceiverAgentID), Valid: true}
	} else {
		receiverAgentID = sql.NullInt64{Int64: 0, Valid: false}
	}

	if !kindBox.ReturnedAt.IsZero() {
		returnedAt = sql.NullTime{Time: kindBox.ReturnedAt, Valid: true}
	} else {
		returnedAt = sql.NullTime{Time: time.Time{}, Valid: false}
	}

	query := `UPDATE kind_boxes SET 
		benefactor_id = ?, type = ?, amount = ?, serial_number = ?, status = ?, deliver_refer_time_id = ?, deliver_refer_date = ?, deliver_address_id = ?, 
        sender_agent_id = ?, delivered_at = ?, return_refer_time_id = ?, return_refer_date = ?, return_address_id = ?, receiver_agent_id = ?, returned_at = ? 
        WHERE 
		id = ? AND deleted_at IS NULL`

	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyKindBoxUpdate, query)
	if err != nil {
		return richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	_, uErr := stmt.ExecContext(ctx,
		kindBox.BenefactorID,
		kindBox.KindBoxType,
		kindBox.Amount,
		kindBox.SerialNumber,
		kindBox.Status,
		kindBox.DeliverReferTimeID,
		kindBox.DeliverReferDate,
		kindBox.DeliverAddressID,
		kindBox.SenderAgentID,
		kindBox.DeliveredAt,
		returnReferTimeID,
		returnReferDate,
		returnAddressID,
		receiverAgentID,
		returnedAt,
		kindBox.ID,
	)

	if uErr != nil {
		return richerror.New(op).WithErr(uErr).WithMessage(errmsg.ErrorMsgCantUpdateRecord).
			WithKind(richerror.KindUnexpected)
	}

	return nil
}
