package mysqlagent

import (
	"context"

	"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) AgentExistByID(ctx context.Context, agentID uint) (bool, error) {
	const op = "mysqladmin.AgentExistByID"

	query := `select count(*) from admins where role = ? and id = ?`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyAdminAgentExistByID, query)
	if err != nil {
		return false, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	var count int
	err = stmt.QueryRowContext(ctx, entity.AdminAgentRole.String(), agentID).Scan(&count)
	if err != nil {
		return false, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
	}

	return count > 0, nil
}
