package mysqlkindboxreq

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

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

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

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

	return k, nil
}
