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) BenefactorKindBoxExist(ctx context.Context, benefactorID, kindBoxID uint) (bool, error) {
	const op = "mysqlkindbox.BenefactorKindBoxExist"

	query := `SELECT COUNT(*) FROM kind_boxes WHERE benefactor_id = ? AND id = ?`
	//nolint
	stmt, err := d.conn.PrepareStatement(ctx, mysql.StatementKeyKindBoxExistForBenefactor, query)
	if err != nil {
		return false, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	var count int
	if err = stmt.QueryRowContext(ctx, benefactorID, kindBoxID).Scan(&count); err != nil {
		return false, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	return count > 0, nil
}

func (d *DB) KindBoxExistForAgent(ctx context.Context, kindBoxID, agentID uint) (bool, error) {
	const op = "mysqlkindbox.KindBoxExistForAgent"

	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 false, richerror.New(op).WithErr(err).
			WithMessage(errmsg.ErrorMsgCantPrepareStatement).WithKind(richerror.KindUnexpected)
	}

	row := stmt.QueryRowContext(ctx, kindBoxID, agentID, entity.KindBoxAssignedReceiverAgentStatus)
	_, err = scanKindBox(row)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return false, nil
		}

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

	return true, nil
}

func (d *DB) KindBoxExist(ctx context.Context, kindBoxID uint) (bool, error) {
	const op = "mysqlkindbox.KindBoxExist"

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

	row := stmt.QueryRowContext(ctx, kindBoxID)
	_, err = scanKindBox(row)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return false, nil
		}

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

	return true, nil
}
