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"
)

func (d DB) KindBoxRequestExist(id uint) (bool, error) {
	op := richerror.Op("mysqlkindboxreq.KindBoxRequestExist")
	row := d.conn.Conn().QueryRow(`select * from kind_box_reqs where id = ?`, id)
	_, sErr := scanKindBoxReq(row)
	if sErr != nil {
		if errors.Is(sErr, sql.ErrNoRows) {
			return false, nil
		}

		return false, richerror.New(op).WithErr(sErr).WithMessage(errmsg.ErrorMsgCantScanQueryResult).
			WithKind(richerror.KindUnexpected).WithMeta(map[string]any{"id": id})
	}

	return true, nil
}

func (d DB) RollbackKindBoxRequestStatus(ctx context.Context, id uint) error {
	op := richerror.Op("mysqlkindboxreq.RollbackKindBoxRequestStatus")
	_, err := d.conn.Conn().ExecContext(ctx, `update kind_box_reqs set status = ? where id = ?`, entity.KindBoxReqPendingStatus.String(), id)
	if err != nil {
		return richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	return nil
}
