package mysqlkindbox

import (
	"context"
	"database/sql"
	"errors"

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

	query := `SELECT * FROM kind_boxes WHERE id = ? AND receiver_agent_id = ? AND status = ? AND deleted_at IS NULL`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyKindBoxGetAwaitingReturnByAgent, query)
	if err != nil {
		return entity.KindBox{}, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	row := stmt.QueryRowContext(ctx, kindBoxID, agentID, entity.KindBoxAssignedReceiverAgentStatus)
	k, err := scanKindBox(row)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return entity.KindBox{}, richerror.New(op).WithErr(err).
				WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindNotFound)
		}

		return entity.KindBox{}, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
	}

	return k, nil
}
