package mysqlkindboxreq

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

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

func (d *DB) GetByID(ctx context.Context, id uint) (entity.KindBoxReq, error) {
	op := richerror.Op("mysqlkindboxreq.GetByID")
	q, cErr := querier.GetQuerierFromContextOrNew(ctx).Continue(ctx, d.conn.Conn())
	if cErr != nil {
		return entity.KindBoxReq{}, richerror.New(op).WithErr(cErr).
			WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
	}
	row := q.Conn().QueryRowContext(ctx, `select * from kind_box_reqs where id = ? and deleted_at is null`, id)
	k, sErr := scanKindBoxReq(row)
	if sErr != nil {
		return entity.KindBoxReq{}, richerror.New(op).WithErr(sErr).
			WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
	}

	return k, nil
}

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

	query := `select * from kind_box_reqs where id = ? and deleted_at is null`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyKindBoxReqGetByID, query)
	if err != nil {
		return entity.KindBoxReq{}, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	row := stmt.QueryRowContext(ctx, kindBoxReqID)
	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
}