package mysqlkindboxreq

import (
	"context"

	"git.gocasts.ir/ebhomengo/niki/entity"
	"git.gocasts.ir/ebhomengo/niki/param"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	builder "git.gocasts.ir/ebhomengo/niki/pkg/query_builder/mysql"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

func (d *DB) GetAllKindBoxReq(ctx context.Context, filter param.FilterRequest, pagination param.PaginationRequest, sort param.SortRequest) ([]entity.KindBoxReq, uint, error) {
	const op = "mysqlkindboxreq.GetAllKindBoxReq"

	baseQuery := `SELECT * FROM kind_box_reqs WHERE deleted_at IS NULL`
	query, args := builder.BuildGetAllQuery(baseQuery, filter, pagination, sort)
	rows, qErr := d.conn.Conn().QueryContext(ctx, query, args...)
	if qErr != nil {
		return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}
	defer rows.Close()
	kindBoxReqs := make([]entity.KindBoxReq, 0)
	for rows.Next() {
		kindBoxReq, sErr := scanKindBoxReq(rows)
		if sErr != nil {
			return nil, 0, richerror.New(op).WithErr(sErr).
				WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
		}
		kindBoxReqs = append(kindBoxReqs, kindBoxReq)
	}

	if rErr := rows.Err(); rErr != nil {
		return nil, 0, richerror.New(op).WithErr(rErr).
			WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	var total uint
	baseQuery = `SELECT COUNT(*) FROM kind_box_reqs WHERE deleted_at IS NULL`
	query, args = builder.BuildGetAllQuery(baseQuery, filter, pagination, sort)
	qErr = d.conn.Conn().QueryRowContext(ctx, query, args...).Scan(&total)
	if qErr != nil {
		return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
	}

	return kindBoxReqs, total, nil
}